# 상속
class 기반클래스이름:
코드
class 파생클래스이름(기반클래스이름): # 기반 클래스를 상속받음
코드
# 기반 클래스의 속성 접근. 메소드 호출.
class 기반클래스이름:
def __init__(self):
self.속성 = 값
class 파생클래스이름(기반클래스이름):
def __init__(self):
super().__init__() # super()로 기반 클래스의 메소드 호출
super().속성 # super()로 기반 클래스의 속성에 접근
super(파생클래스, self).속성 # super에 파생 클래스와 self를 넣는 형식
# 상속 관계 확인하기
issubclass(파생클래스, 기반클래스)
# 사람 클래스로 학생 클래스 만들기
class Person:
def greeting(self):
print('안녕하세요.')
class Student(Person):
def study(self):
print('공부하기')
james = Student()
james.greeting() # 안녕하세요 : 기반클래스의 메소드 호출
james.study() # 공부하기 : 파생클래스에 추가한 메소드
class Person:
def greeting(self):
print('안녕하세요.')
class PersonList():
def __init__(self):
self.person_list = [] # 리스트 속성에 Person 인스턴스를 넣어서 관리
def append_person(self, person): # 리스트 속성에 Person 인스턴스를 추가하는 함수
self.person_list.append(person)
__init__ 메소드를 호출해주면 기반 클래스가 초기화되어서 속성이 만들어짐super().메소드()

class Person:
def __init__(self):
print('Person __init__')
self.hello = '안녕하세요'
class Student(Person):
def __init__(self):
print('Student __init__')
super().__init__()
self.school = '파이썬 코딩 도장'
james = Student()
print(james.school)
print(james.hello) # 기반 클래스의 속성 출력
__init__ 를 생략한다면 기반 클래스의 __init__이 자동으로 호출되어 super() 사용하지 않아도 됨super()은 파생 클래스와 self를 넣어서 현재 클래스가 어떤 클래스인지 알 수 있음super(파생클래스, self).메소드
class Student(Person):
def __init__(self):
print('Student' __init__')
super(Student, self).__init))() # super(파생클래스, self)로 기반 클래스의 메소드 호출
self.school = '파이썬 코딩 도장'
class Person:
def greeting(self):
print('안녕하세요')
class Student(Person):
def greeting(self):
super().greeting() # 기반 클래스의 메소드 호출하여 중복 줄임
print('저는 파이썬 코딩 도장 학생입니다.')
james = Student()
james.greeting()
class 기반클래스이름1:
코드
class 기반클래스이름2:
코드
class 파생클래스이름(기반클래스이름1, 기반클래스이름2):
class Person:
def greeting(self):
print('안녕하세요')
class University:
def manage_credit(self):
print('학점 관리')
class Undergraduate(Person, University):
def study(self):
print('공부하기')
james = Undergraduate()
james.greeting() # 안녕하세요 : 기반 클래스 Person의 메소드 호출
james.manage_cradit() # 학점 관리 : 기반 클래스 University의 메소드 호출
james.study() # 공부 하기 : 파생 클래스 Undergraduate에 추가한 study 메소드
from abc import *
class 추상클래스이름(metaclass=ABCMeta):
@abstractmethod
def 메소드이름(self):
코드
from abc import *
class StudentBase(metaclass=ABCMeta): # 추상 클래스
@abstracmethod
def study(self): # 추상 메소드 정의
pass
@abstractmethod
def go_to_school(self): # 추상 메소드 정의
pass
class Student(StudentBase): # 추상 클래스 상속받음
def study(self): # 추상 메소드 구현
print('공부하기')
def go_to_school(self): # 추상 메소드 구현
print('학교가기')
james = Student()
james.study() # 파생 클래스 인스턴스 생성
james.go_to_school() # 파생 클래스 인스턴스 생성
"마나약 어떤 새가 오리처럼 걷고, 헤엄치고, 꽥꽥거리는 소리를 낸다면 나는 그 새를 오리라 부르겠다"
__init__ 메소드를 구현하지 않음