Dev./Python

Python - 클래스 상속 (Inheritance)

Ivan'show 2023. 6. 12.
728x90
반응형
  • 기존 클래스에서 새 클래스를 파생하여 새 클래스가 기존 클래스의 모든 멤버(변수와 메서드)를 상속 하는 메커니즘을 상속 또는 유도라고 한다.
  • Old Class >>>>>>>>>>> New Class
  • 기존 클래스를 슈퍼 클래스 (Super Class) 라고 하며, 새 클래스를 서브 클래스 (Sub Class) 라고 한다.자식 클래스, 파생 클래스, 새 클래스, : 서브 클래스
  • 부모 클래스, 기존 클래스, 기본 클래스 : 슈퍼 클래스
  • 파이썬의 모든 클래스는 object 라는 단일 슈퍼 클래스로부터 빌드되므로, 파이썬에서 클래스를 생성하면 내부적으로 object 가 슈퍼 클래스가 된다.
  • 상속의 주요 장점은 코드 재사용성이다.
  • 상속의 종류
    • 단일 상속 (single Inheritance)
    • 다중 레벨 상속 (muti-level Inheritance)
    • 계층 상속 (hierarchical Inheritance)
    • 다중 상속 (multiple Inheritance)

자식 클래스 선언

# 자식 클래스 선언
# 인자로 부모 클래스를 받아서 선언
class ChildClassName (ParentClassName):
    members of Child class

단일 상속

object
|
|
Father # Parent Class
|
|
Son # Child Class

다중 레벨 상속

object
|
|
Father # Parent Class
|
|
Son # Child Class
|
|
GrandSon # GrandChild Class

계층 상속

object
|
|
Father # Parent Class
|
|________________________
|           |           |
Son      Daughter      Son2 # Child Class

다중 상속

object
|
|_______________
|              |
Parent1      Parent2 # Parent Class
\\             /
   \\        /
      \\   /
      Child # Child Class

네임 스페이스

  • 클래스 네임 스페이스
  • 클래스는 자체 네임스페이스를 유지하며 이를 클래스 네임스페이스라고 한다. 클래스 네임스페이스에서 이름은 클래스 변수에 매핑된다.
  • 인스턴스 네임 스페이스
  • 모든 인스턴스는 자체 네임스페이스를 가지며 이를 인스턴스 네임스페이스라고 한다. 인스턴스 네임스페이스에서 이름은 인스턴스 변수에 매핑된다.
class Mobile:
    fp = 'yes'

realme = Mobile()  # 생성자 함수: 클래스를 메모리공간에 띄워주고 앞 변수가 클래스의 기능을 가져다 쓸 수 있게 한다.
redme = Mobile()
geek = Mobile()

print(Mobile.fp)
print(realme.fp)
print(redme.fp)
print(geek.fp)
# yes
# yes
# yes
# yes

Mobile.fp = 'no'  # 클래스 네임스페이스에 있는 변수를 변경하면 이미 클래스를 전달받은 모든 내용에도 영향을 준다.

print(Mobile.fp)
print(realme.fp)
print(redme.fp)
print(geek.fp)
# no
# no
# no
# no

realme.fp = 'realme?'  # 인스턴스 네임스페이스에 있는 변수를 변경하면 범위가 고정되어 변경된다.

print(Mobile.fp)
print(realme.fp)
print(redme.fp)
print(geek.fp)
# no
# realme?
# no
# no

오버로드 & 오버로딩

  • 메소드 오버로딩은 같은 이름의 메소드를 여러개 가지면서 매개변수의 유형과 개수를 다르게 하는 기술
  • 메소드 오버라이딩은 하위 클래스가 상위 클래스의 메소드를 재정의하는 기술
class ParentClass:
    def __init__(self):
        self.name = 'parent'
        self.number = 10

    def __str__(self):
        return f'ParentClass name : {self.name}, number : {self.number}'

    def add_num(self, new_number):
        print('부모 : ', new_number, '만큼 더해야지')
        self.number = self.number + new_number

    def minus_num(self, new_number):
        print('부모 : ', new_number, '만큼 빼야지')
        self.number = self.number - new_number

    def multiple_num(self, new_number):
        print('아낌없이 주는 부모 : 자식아 넌 곱하기 함수 없지? 괜찮아 내가 줄게')
        self.number = self.number * new_number

class ChildClass(ParentClass):  # 부모 클래스 상속
    def __init__(self):
        super().__init__()
        self.name = 'child'
        self.number = 10

    def __str__(self):
        return f'ChildClass name : {self.name}, number : {self.number}'

    def add_num(self, new_number):  # 부모 클래스에 있던 add_num 메소드를 오버라이딩(Overriding)
        print('말 안듣는 자식 : 고정적으로 5 더할껀데?')
        self.number = self.number + 5

    def minus_num(self, new_number):  # 부모 클래스에 있던 minus_num 메소드를 오버라이딩(Overriding)
        print('말 안듣는 자식 : 난 고정적으로 5 뺄껀데?')
        self.number = self.number - 5

    def discipline(self, order, *num):  # 파이썬은 오피셜로는 오버로딩을 지원하지 않는다. 대신 이렇게 유사하게 가능
        if order == '상냥한 말투':
            print('말 안듣는 자식 : ', num[0], ' 이 숫자 마음에 안들어')
        elif order == '말좀 들어라':
            print('말 듣는 자식 : ', num[0], ', ', num[1], ' 이 숫자 마음에 들어요')

parent = ParentClass()
child = ChildClass()
print('클래스 정보')
print(parent)
print(child)
print()
# 클래스 정보
# ParentClass name : parent, number : 10
# ChildClass name : child, number : 10

print('7을 더하세요')
parent.add_num(7)
child.add_num(7)
print(parent)
print(child)
print()
# 7을 더하세요
# 부모 :  7 만큼 더해야지
# 말 안듣는 자식 : 고정적으로 5 더할껀데?
# ParentClass name : parent, number : 17
# ChildClass name : child, number : 15

print('7을 빼세요')
parent.minus_num(7)
child.minus_num(7)

print(parent)
print(child)
print()
# 7을 빼세요
# 부모 :  7 만큼 빼야지
# 말 안듣는 자식 : 난 고정적으로 5 뺄껀데?
# ParentClass name : parent, number : 10
# ChildClass name : child, number : 10

print('자식만 10 곱하기')
child.multiple_num(10)
print(child)

print('훈육시키기')
child.discipline('상냥한 말투', 1)
child.discipline('말좀 들어라', 10, 20)
# 자식만 10 곱하기
# 아낌없이 주는 부모 : 자식아 넌 곱하기 함수 없지? 괜찮아 내가 줄게
# ChildClass name : child, number : 100
# 훈육시키기
# 말 안듣는 자식 :  1  이 숫자 마음에 안들어
# 말 듣는 자식 :  10 ,  20  이 숫자 마음에 들어요
728x90
반응형

'Dev. > Python' 카테고리의 다른 글

Python - 배열  (1) 2023.06.13
Python - 패키지  (0) 2023.06.12
Python - 함수 : 작동원리, return, 기본값, 가변, 키워드  (0) 2023.06.11
Python - Generator  (0) 2023.06.10
Python - Dictionary  (0) 2023.06.09

댓글