-
[코딩도장] day25. 파이썬 클래스 상속 사용하기(1/2) - 클래스 상속, super(), 오버라이딩IT/파이썬 2020. 9. 19. 01:39
출처 : unsplash ■ 들어가기
- 파이썬 코딩 도장 (남재윤/길벗). 을 공부하며 정리하는 블로그
▶ Unit36. 클래스 상속 사용하기
- 36.1 사람 클래스로 학생 클래스 만들기
- 36.2 상속 관계와 포함 관계 알아보기
- 36.3 기반 클래스의 속성 사용하기
- 36.4 메서드 오버라이딩 사용하기
- 36.5 다중 상속 사용하기
- 36.6 추상 클래스 사용하기
0. 들어가기
- 클래스 상속?? 상위 클래스로부터 물려받은 기능을 유지한 채 다른 기능을 추가할 때 사용하는 기능
- 물려주는 상위 클래스를 "기반 클래스" (부모 클래스, 슈퍼 클래스라 부르기도 함)
물려받는 하위 클래스를 "파생 클래스" 라 부름 (자식 클래스, 서브 클래스라 부르기도 함)
출처 : 파이썬 코딩 도장 (dojang.io) - 상속은 기존 기능을 재사용할 수 있어서 효율적
( 새로운 기능 필요시 마다 클래스를 만들면 중복되는 부분을 반복해서 만들어야 하기 때문 )
>> 36.1 사람 클래스로 학생 클래스 만들기 <<
- 사용법
class 기반클래스이름 :
코드
class 파생클래스이름(기반클래스이름) :
코드
소스 (class_inheritance.py) 결과 class Person :
def greeting(self) :
print('안녕하세요.')
class Student(Person) :
def study(self) :
print('공부하기')
james = Student()
james.greeting()
jaems.study()안녕하세요.
공부하기- Student 클래스에는 greeting 메서드가 없지만 상속을 통해 greeting 메서드 호출 가능
출처 : 파이썬 코딩 도장 (dojang.io) [참고] 상속 관계 확인하기
- issubclass 함수로 클래스의 상속 관계 확인
- 사용법 : issubclass(파생클래스, 기반클래스)
- 기반 클래스의 파생 클래스가 맞다면 True, 아니면 False 를 반환
>>> class Person :
pass
>>> class Student(Person) :
pass
>>> issubclass(Student, Person)
True
>> 36.2 상속 관계와 포함 관계 알아보기 <<
1. 상속 관계 (is-a 관계)
- 상속은 명확하게 같은 종류이며 동등한 관계일 때 사용
- "학생(Student)은 사람(Person)이다."라고 했을 때 말이 되면 동등한 관계임
2. 포함 관계 (has-a 관계)
- 속성에 인스턴스를 넣어 관리
>> 36.3 기반 클래스의 속성 사용하기 <<
소스 (class_inheritance_attribute_error.py) 결과 class Person :
def __init__(self) :
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person) :
def __init__(self) :
print('Student __init__')
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello)Student __init__
파이썬 코딩 도장
Traceback (most recent call last):
File "C:/project/class_inheritance_attribute_error.py", line 14, in <module>
print(james.hello)
AttributeError: 'Student' object has no attribute 'hello'- 에러 : Student 객체에서 hello 속성 호출 불가
- 원인 : Person 클래스의 __init__ 메서드가 호출되어야 hello 속성 생성되는데, 해당 메서드가 호출되지 않음
1. super()로 기반 클래스 초기화하기
- 위와 같은 경우 super()를 사용해서 기반 클래스(Person)의 __init__ 메서드 호출
- 사용법 : super().메서드()
소스 (class_inheritance_attribute.py) 결과 class Person :
def __init__(self) :
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person) :
def __init__(self) :
print('Student __init__')
super().__init__() # 기반클래스의 __init__ 메서드 호출
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello)Student __init__
Person __init__
파이썬 코딩 도장
안녕하세요.2. 기반 클래스를 초기화하지 않아도 되는 경우
- 파생 클래스에서 __init__ 메서드를 생략한다면 기반 클래스의 __init__이 자동으로 호출됨
=> super() 사용하지 않아도 됨
소스 (class_inheritance_no_init.py) 결과 class Person :
def __init__(self) :
print('Person __init__')
self.hello = '안녕하세요.'
class Student(Person) :
pass
james = Student()
print(james.hello)Person __init__
안녕하세요.
>> 36.4 메서드 오버라이딩 사용하기 <<
- 오버라이딩?? 파생 클래스에서 기반 클래스의 메서드를 새로 정의하는 방법
소스 (class_method_override.py) 결과 class Person :
def greeting(self) :
print('안녕하세요.')
class Student(Person) :
def greeting(self) :
print('안녕하세요. 저는 파이썬 코딩 도장 학생입니다.')
james = Student()
james.greeting()안녕하세요. 저는 파이썬 코딩 도장 학생입니다. - super() 로 기반 클래스 메서드 호출하기 + 재정의하기
소스 (class_method_overriding_super.py) 결과 class Person :
def greeting(self) :
print('안녕하세요.')
class Student(Person) :
def greeting(self) :
super().greeting() # 기반 클래스의 메서드 호출
print('저는 파이썬 코딩 도장 학생입니다.')
james = Student()
james.greeting()안녕하세요.
저는 파이썬 코딩 도장 학생입니다.'IT > 파이썬' 카테고리의 다른 글
[코딩도장] day26. 파이썬 두 점 사이의 거리 구하기 (0) 2020.09.19 [코딩도장] day26. 파이썬 클래스 상속 사용하기(2/2) - object클래스, 다중 상속, 추상 클래스 (0) 2020.09.19 [코딩도장] day24. 파이썬 클래스 속성과 정적, 클래스 메서드 사용하기 (0) 2020.09.18 [코딩도장] day23. 클래스 사용하기 (0) 2020.09.16 [코딩도장] day23. 클로저 사용하기 (0) 2020.09.16