[Python] 파이썬 메서드 오버라이딩 (method overriding)
오버라이딩_overriding (재정의)
: 부모로 부터 받은 메서드 내용을 자식 클래스에 맞게 내용을 변경하는 것
오버라이딩의 조건 : 메서드 이름이 동일해야 한다.
#overriding1.py
class Animal:
def __init__(self,name):
self.name = name
def cry(self):
pass
class Puppy(Animal):
def __init__(self,name,age):
self.name = name
self.age = age
def cry(self):
print("DOGsound")
class Cat(Animal):
def __init__(self,name,age):
self.name = name
self.age = age
def cry(self):
print("CatSound")
doggy = Puppy("DOGGY",1)
doggy.cry()
cat = Cat("cat",1)
cat.cry()
부모클래스에게 받은 메서드 보다 우선적으로 호출된다.
자식 클래스가 부모클래스를 호출하고 싶은 경우 사용하는 메서드
super()
사용방법 : 메서드super().부모클래스의 내용
#overriding2.py
class point:
def __init__(self,x,y):
self.x =x
self.y= y
def draw(self):
print("x>>",self.x)
print("y>>",self.y)
class point3d(point):
def __init__(self,x,y,z):
self.x =x
self.y= y
self.z= z
#method overrding
def draw(self):
super().draw() #부모클래스(super)의 메서드가 호출된다.
print("z>>",self.z) #부모클래스에 없는 것만 추가된 부분
c1 = point3d(10,10,10)
c1.draw()
부모클래스 생성자 호출 할때 부모의 객체를 생성하는 방법
MRO : 파이썬의 클래스 탐색 순서를 나타내는 메서드
객체지향언어는 기본적으로 object 클래스를 자동적으로 상속 받는다.
#overriding3.py
class A:
def __init__(self,a):
self.a = a #a 의 초기화를 위해서 클래스 B의 A생성자를 통해 진행해야한다.
print('Class A')
class B(A):
def __init__(self):
super().__init__(10) #부모의 생성자를 super를 통해 호출할 수 있다.
print('Class B')
class C(B):
def __init__(self):
super().__init__() #부모의 생성자를 super를 통해 호출할 수 있다.
print('Class C')
c1 = C()
print(C.mro())
#overriding4.py
class Shape:
def __init__(self,x,y):
self.x = x
self.y = y
print("parent")
def draw(self):
pass
class Rect(Shape):
def __init__(self,x,y):
super().__init__(x,y) #super
print("Rect")
#overriding
def draw(self):
print("rectangle")
print("width : ",self.x)
print('height : ',self.y)
r1 = Rect(10,10)
r1.draw()
*실습
댓글
댓글 쓰기