Python/파이썬 기초
[Python] 상속과 오버라이드
isfp_yykkng
2023. 2. 22. 18:40
상속과 오버라이드
상속 (Inheritance)
상속 : 자식 클래스가 부모 클래스의 내용을 가져다 쓸 수 있는 것 (상속하는 클래스를 부모 클래스, 상속받는 클래스를 자식 클래스라 부르고 상속을 하면 부모의 것이 없어지는 것은 아니다.)
상속받는 방법
class <자식클래스명> ( <부모클래스명> ) :
상속받는 방법은 상속받을 자식클래스의 매개변수로 부모클래스를 받는 것이다. 상속을 받게되면 자식클래스는 부모클래스의 메서드나 변수를 사용할 수 있다.
상속 예제
class Animal( ):
def walk( self ):
print( "걷는다" )
def eat( self ):
print( "먹는다" )
class Human( Animal ):
def wave( self ):
print( "손을 흔든다" )
class Dog( Animal ):
def wag( self ):
print( "꼬리를 흔든다" )
오버라이드
오버라이드 (override) : 같은 이름을 가진 메서드를 덮어 쓴다는 의미
class Animal( ):
def greet( self ):
print( "인사한다" )
class Human( Animal ):
def greet( self ): # 부모의 greet 메서드를 오버라이드
print( "손을 흔든다" )
class Dog( Animal ):
def greet( self ): # 부모의 greet 메서드를 오버라이드
print( "꼬리를 흔든다" )
class Cow( Animal ):
'''소'''
# 오버라이드 하지 않음
human = Human()
human.greet() # 손을 흔든다
dog = Dog()
dog.greet() # 손을 흔든다
cow = Cow()
cow.greet() # 인사한다
super() 함수
super 함수는 자식클래스에서 부모클래스의 내용을 사용하고 싶은 경우 사용한다.
super(). <부모클래스 내용>
class Animal( ):
def __init__( self, name ):
self.name = name
def greet(self):
print("{}이/가 인사한다".format(self.name))
class Human( Animal ):
def __init__( self, name, hand ):
super().__init__( name ) # 부모클래스의 __init__ 메소드 호출
self.hand = hand
def wave(self):
print("{}을 흔들면서".format(self.hand))
def greet(self): # greet 함수 오버라이드
self.wave()
super().greet()
person = Human( "사람", "오른손" )
person.greet() # 오른손을 흔들면서 사람이/가 인사한다