다음은 Python에서 다형성 동작을 학습하는 동안 함께 작업하고있는 코드의 예입니다. 제 질문은 show_affection과 비슷한 기능을 두 번 선언해야하는 이유는 무엇입니까? 호출자 (메서드를 호출하는 인스턴스)가 Dog인지 확인하고, 고양이 인 경우 다른 작업을 수행하십시오.코드를 유지하기 위해 다형 메소드를 리팩토링하는 방법 DRY
아래 예제 코드에서 볼 수 있듯이 show_affection은 Animal을 상속 한 Cat 클래스와 Dog 클래스에서 모두 정의됩니다.
동물 클래스에서 show_affection을 선언하지 않는 이유는 무엇입니까?하지만 발신자를 확인하는 방법을 모르겠습니다.
다음def show_affection(self):
If caller is the Dog instance:
print("{0}.barks".format(self.name))
else:
print("{0}.wags tail".format(self.name))
처럼 내가 Cat.show_affection()
이 Dog.show_affection()
다른 무언가를하기 때문 "자신을 반복"의 예 아닙니다
class Animal(object):
def __init__(self, name):
self.name = name
def eat(self, food):
print("{0} eats {1}".format(self.name, food))
class Dog(Animal):
def fetch(self, thing):
print("{0} goes after the {1}".format(self.name, thing))
def show_affection(self):
print("{0} wags tail".format(self.name))
class Cat(Animal):
def swatstring(self):
print("{0} shreds the string".format(self.name))
def show_affection(self):
print("{0} purrs".format(self.name))
for a in (Dog('rover'), Cat('fluffy'), Cat('precious'), Dog('Scout')):
a.show_affection()
a.eat('bananas')
이것은 '동물'클래스가 잠재적 인 하위 클래스를 모두 알아야한다는 것을 의미합니다. 이는 매우 확장 성이 없다는 것을 의미합니다 ... 나는 DRY와 같은 원리를 적용하는 것에 대해주의해야합니다. 하지만 귀하의 질문에 대답하기 위해'type (self) == Dog'을 테스트 할 수 있습니다 – AChampion
감사합니다 @AChampion – Stryker