** 파이썬은 다형성을 느슨하게 구현했다. 이것은 클래스에 상관없이 같은 동작을 다른 객체에 적용할 수 있다는 것을 의미 한다. **
class Quote():
def __init__(self, person, words):
self.person = person
self.words = words
def who(self):
return self.person
def says(self):
return self.words + '.'
class QuestionQuote(Quote):
def says(self):
return self.words + '?'
class ExclamationQuote(Quote):
def says(self):
return self.words + '!'
hunter = Quote('Elmer Fudd', "I'm hinting wabbits")
print(hunter.who(), 'says:', hunter.says())
Elmer Fudd says: I’m hinting wabbits.
hunted1 = QuestionQuote('Bugs Bunny', "What's up, doc")
print(hunted1.who(), 'says:', hunted1.says())
Bugs Bunny says: What’s up, doc?
hunted2 = ExclamationQuote('Daffy Duck', "It's rabbit season")
print(hunted2.who(), 'says:', hunted2.says())
Daffy Duck says: It’s rabbit season!
class BabblingBrook():
def who(self):
return 'Brook'
def says(self):
return 'Babble'
brook = BabblingBrook()
def who_says(obj):
print(obj.who(), 'says', obj.says())
who_says(hunter)
who_says(hunted1)
who_says(hunted2)
who_says(brook)
Elmer Fudd says I’m hinting wabbits. Bugs Bunny says What’s up, doc? Daffy Duck says It’s rabbit season! Brook says Babble
다양한 객체의 who() 와 says()를 실행 할 수 있다. brook 객체는 다른 객체와 전혀 관계가 없다.
Comments