6.4 메서드 오버라이드

class Car():
def exclaim(self):
print("I'm a Car!")
class Yugo(Car):
def exclaim(self):
print("I'm a Yugo! Much like a Car, but more Yugo-ish.")
give_me_a_car = Car()
give_me_a_yugo = Yugo()
give_me_a_car.exclaim()
give_me_a_yugo.exclaim()

I’m a Car! I’m a Yugo! Much like a Car, but more Yugo-ish.

exclaim() 메서드를 오버라이드 했다. 우리는 __init__() 메서드를 포함한 모든 메서드를 오버라이드 할수 있다.

class Person():
def __init__(self, name):
self.name = name
class MDPerson(Person):
def __init__(self, name):
self.name = "Doctor " + name
class JDPerson(Person):
def __init__(self, name):
self.name = name + ", Esquire"
person = Person('Fudd')
doctor = MDPerson('Fudd')
lawyer = JDPerson('Fudd')
print(person.name)
print(doctor.name)
print(lawyer.name)

Fudd Doctor Fudd Fudd, Esquire

Comments