How to refactor polymorphic method to keep code DRY
<p>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.</p>

<p>As you can see in the example code below, show_affection is defined in both Cat and Dog classes which inherit from Animal.</p>

<p>Why not declare show_affection in the Animal Class but I am not sure how to check for the caller. like</p>

<pre><code>def show_affection(self):

    If caller is the Dog instance:
        print("{0}.barks".format(self.name))
    else:
        print("{0}.wags tail".format(self.name))
</code></pre>

<p>Here is the what I have</p>

<pre><code>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')
</code></pre>

<p>This is not an example of "repeating yourself", because <code>Cat.show_affection()</code> does something different from <code>Dog.show_affection()</code>.  If the two methods were the same, then you could avoid repetition by defining the implementation once in <code>Animal</code>.  But since you want to have different behaviors for <code>Cat</code> and <code>Dog</code>, the correct way to do it is to implement the method in each class.</p>

<p>In general:</p>

<ul>
<li>Cat-specific behaviors should be defined in <code>Cat</code>.</li>
<li>Dog-specific behaviors should be defined in <code>Dog</code>.</li>
<li>Behaviors that apply to all animals should be defined in <code>Animal</code>.</li>
</ul>

python polymorphism