Search code examples
pythonclassobjectinheritancemethod-resolution-order

Python & Classes - Can I use a method in a superclass that is going to be created in a subclass?


hope that you're all fine. I need to do some home-work, I came up with a doubt that I don't know if it can be resolved in this way. Do you mind if you can help me? Thanks anyway.

Suppose we have this:

class human:
    def dress(self, weather):
        return color(weather)

class girl(human):
    def color(self, weather):
        if weather == 'rainy':
            print('red')
        else:
            print('blue')

Can I do this? Because at first sight I have a problem that color(), at Human, is undefined (logically). You may ask, why are you thinking this way? Because are the instructions to solve the problem. Which is the best solve it?

Thanks again!


Solution

  • Yes, you can do that. It's not uncommon to have methods in a superclasses that are left to be defined by the subclasses. Usually the superclass will have a placeholder implementation that throws an exception indicating that the subclass needs to define it - however that isn't required for this to work.

    class human:
        def dress(self, weather):
            return self.color(weather)
    
        def color(self, weather):
            raise NotImplementedError("Subclass needs to define this.")
    
    class girl(human):
        def color(self, weather):
            if weather == 'rainy':
                c = 'red'
            else:
                c = 'blue'
            print(c)
            return c
    

    Some base classes aren't meant to be used directly and require the subclass to implement methods that the base class calls. If you subclass such a class and fill in the implementation for the needed methods.. the methods that the base class already has defined which calls them will work.

    For instance, say we have a girl instance. And we want it to dress for the weather. Even though the subclass doesn't define dress() it still has that method because it inherited it.

    >>> mary = girl()
    >>>
    >>> mary.dress("rainy")
    red
    

    At runtime, the interpreter runs the code for dress() and in it sees color(). It then looks for that function on the girl and finds it. Doesn't matter whether the base class defines it or not.