class FishBread:
def __init__(self, f, b):
self.flour=f
self.bean=b
def makeFishBread(self):
print("붕어빵 제조")
def add(self):
print()
✔️ 기반 클래스 : 기능을 물려주는 클래스
✔️ 파생 클래스 : 상속을 받아 새롭게 만드는 클래스
class Person:
def greeting(self):
...
class Student(Person):
def study(self):
...
이때 기반클래스는 Person이고
파생클래스는 Student이다.
james = Student()
james.greeting()
james.study()
○ 상속관계 : 명확하게 같은 종류이며 동등한 관계일 때 사용
• "학생은 사람이다." 라고 했을 때 말이 되면 동등한 관계
○ 포함관계 : 아래 예시 참고
class Person:
def greeting(self):
...
class PersonList():
def __init__(self):
self.person_list=[]
def append_person(self, person):
self.person_list.append(person)
✔️ 기반클래스의 속성 사용하기
class Person:
def __init__(self):
self.hello = ...
class Student(Person):
def__init__(self):
super().__init__()
self.school = ...
위와 같이 파생클래스에서 super()로 기반클래스의 속성을 가져와야 사용할 수 있다.
class Adress:
def __init__(self, street, city):
self.street = str(street)
self.city = str(city)
class Person:
def __init__(self, name, email):
self.name = str(name)
self.email = str(email)
class Contact(Adress, Person):
def __init__(self, street, city, name, email):
Adress.__init__(self, street, city)
Person.__init__(self, name, email)
만약 파생클래스에서 init 메서드를 생략한다면 기반클래스의 속성들이 자동으로 호출된다.
class Person:
def __init__(self):
self.hello = ...
class Student(Person):
pass
✔️ 메서드 오버라이딩 사용하기
• 기반클래스의 메서드를 무시하고 새로운 메서드를 만든다는 뜻
• 기반클래스의 메서드를 재활용하여 중복을 줄일 수 있다.
class Person:
def greeting(self):
print('a')
class Student(Person):
def greeting(self):
super().greeting()
print('b')
james = Student()
james.greeting()
• 실행결과
a
b
class Person:
def greeting(self):
print("hi")
class University:
def manage_credit(self):
print("manage")
class Undergraduate(Person, University):
def study(self):
print("study")
james = Undergraduate()
james.greeting()
james.manage_credit()
james.study()
# 모두가능!
• 메서드의 목록만 가진 클래스이며 상속받는 클래스에서 메서드 구현을 강제하기 위해 사용함
• 파생클래스가 반드시 구현해야 하는 메서드를 정해줄 수 있다. -> 구현하지 않으면 에러가 발생하게 해준다.
from abc import *
class 클래스이름(metaclass=ABCMeta):
@abstractmethod
def 메서드이름(self):
코드