상속
- 클래스는 상속이 가능함
- 모든 파이썬 클래스는 object를 상속받음
- 상속을 통해 객체간의 관계를 구축
- 부모 클래스의 속성, 메서드가 자식 클래스에 상속되므로 코드 재사용성이 높아짐
class Person:
population = 0
def __init__(self, name='사람'):
self.name = name
Person.population += 1
def talk(self):
print(f'반갑습니다. {self.name}입니다.')
class Student(Person): # 상속
def __init__(self, student_id, name='학생'):
self.name = name
self.student_id = student_id
Person.population += 1
isinstance
isinstance(object, classinfo)
object가 classinfo의 instance거나 subclass의 instance인 경우 True
print(isinstance(s1, Student))
print(isinstance(s1, Person))
=> True
=> True
issubclass
- issubclass(class, classinfo)
- class가 classinfo의 subclass면 True
- classinfo 는 클래스 객체의 튜플일 수 있으며, classinfo의 모든 항목을 검사함
print(issubclass(Student, Person))
print(issubclass(bool, int))
=> True
=> True # bool이 int를 상속받기 때문에, int -> bool로 암시적 형변환이 가능한 것!super()
- 자식클래스에서 부모클래스를 사용하고 싶은 경우
- 특히 자식 클래스에서 생성자 함수를 정의할 시 중복되는 코드를 작성하지 않기 위해 사용할 수 있음
Person.__init__()==super().__init__()이다.
class Person:
def __init__(self, name, age, number, email):
self.name = name
self.age = age
self.number = number
self.email = email
def greeting(self):
print(f'안녕, {self.name}')
class Student(Person):
def __init__(self, name, age, number, email, student_id):
# Person 클래스
super().__init__(name, age, number, email)
self.student_id = student_id
메서드 오버라이딩(method overriding)
- 상속 받은 메서드를 재정의
- 상속받은 클래스에서 부모 클래스에게 물려받은 메서드를 재정의하여 덮어 쓰는 것
- 부모 클래스의 메서드를 실행시키고 싶은 경우 super를 활용
class Person:
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = number
def talk(self):
print(f'안녕, {self.name}')
class Soldier(Person):
def __init__(self, name, age, number, army):
super().__init__(name, age, number)
self.army = army
# method overriding
def talk(self):
super().talk() # 우선 부모 클래스의 메서드 호출
print(f'그리고 내 계급은 {self.army}')
정리
- 파이썬의 모든 클래스는 object로부터 상속됨
- 부모 클래스의 모든 요소(attribute, method)가 상속됨
- super()을 통해 부모 클래스의 요소를 호출할 수 있음
- 메서드 오버라이딩을 통해 자식 클래스에서 재정의 가능함
- 상속관계에서의 이름 공간은 인스턴스, 자식 클래스, 부모 클래스 순으로 탐색
다중상속
- 두 개 이상의 클래스를 상속 받는 경우 다중 상속이 됨
- 상속받은 모든 클래스의 요소를 활용 가능
- 상속받은 클래스들에 중복되는 속성이나 메서드가 있는 경우, 상속 순서에 따라 상속받는 속성이나 메서드가 결정됨
class Mom(Person):
gene = 'XX'
def swim(self):
return '첨벙첨벙'
class Dad(Person):
gene = 'XY'
def walk(self):
return '성큼성큼'
class FirstChild(Dad, Mom):
def swim(self): # Mom의 swim 메서드를 오버라이딩 합니다.
return '챱챱'
def cry(self): # Child 만이 가지는 인스턴스 메서드 입니다.
return '응애'
## 이제 baby 인스턴스를 생성해보고, 확인
baby = FirstChild('sungu')
baby.walk() # Dad 클래스의 walk 메서드 상속
baby.swim() # Mom 클래스의 메서드를 상속받지만, 오버라이딩 한다.
baby.gene # Dad 클래스가 선행하므로, Dad 클래스의 gene 속성을 우선적으로 상속받음
=> '성큼성큼'
=> '챱챱'
=> 'XY' 'Python' 카테고리의 다른 글
| pip freeze - 패키지 관리 (0) | 2021.09.02 |
|---|---|
| 가상환경 (0) | 2021.09.01 |
| 클래스와 인스턴스 (0) | 2021.08.30 |
| 객체지향 프로그래밍 (0) | 2021.08.30 |
| 객체 (0) | 2021.08.30 |
댓글