Python
Python 문법 기초 27 - class method override(재정의), 다형성
코딩탕탕
2022. 10. 22. 17:09
# method override(재정의)
class Parent:
def printData(self):
pass
class Child1(Parent):
def printData(self): # method override(재정의)
print('Child1에서 재정의')
class Child2(Parent):
def printData(self): # method override(재정의)
print('Child2에서 override')
print('오버라이드는 부모의 메소드를 자식이 재정의')
def abc(self):
print('Child2 고유 메소드')
c1 = Child1()
c1.printData()
print()
c2 = Child2()
c2.printData()
<console>
Child1에서 재정의
Child2에서 override
오버라이드는 부모의 메소드를 자식이 재정의
부모 클래스의 메소드를 재정의 할 때는 자식 클래스 안에서 같은 메소드 명으로 재정의 할 수 있다.
print('--다형성--')
# par = Parent()
par = c1
par.printData()
print()
par = c2
par.printData()
par.abc()
<console>
--다형성--
Child1에서 재정의
Child2에서 override
오버라이드는 부모의 메소드를 자식이 재정의
Child2 고유 메소드
plist = [c1, c2]
for i in plist:
i.printData()
<console>
Child1에서 재정의
Child2에서 override
오버라이드는 부모의 메소드를 자식이 재정의
함수 2개를 list 타입에 넣고 반복문으로 순서대로 호출할 수도 있다.