Reputation: 6130
Here is an example of the code I am working with while learning polymorphic behaviour in python. My question is: Why do I have to declare the very similar function of show_affection twice? Why not check if the caller (the instance calling the method) and if it is Dog, do one thing, if it is a cat do another.
As you can see in the example code below, show_affection is defined in both Cat and Dog classes which inherit from Animal.
Why not declare show_affection in the Animal Class but I am not sure how to check for the caller. like
def show_affection(self):
If caller is the Dog instance:
print("{0}.barks".format(self.name))
else:
print("{0}.wags tail".format(self.name))
Here is the what I have
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')
Upvotes: 0
Views: 53
Reputation: 13096
This is not an example of "repeating yourself", because Cat.show_affection()
does something different from Dog.show_affection()
. If the two methods were the same, then you could avoid repetition by defining the implementation once in Animal
. But since you want to have different behaviors for Cat
and Dog
, the correct way to do it is to implement the method in each class.
In general:
Cat
.Dog
.Animal
.Upvotes: 1