Search code examples
pythoninheritancemultiple-inheritancesuperclass

Use of super () in python


When I execute the following:

class animal(object):
      def desc(self):
             print 'animal'
class human():
      def desc(self):
              print 'human'
class satyr(human, animal):
      def desc(self):
              print 'satyr'

grover=satyr()
super(satyr, grover).desc()

I get human! But human did not even inherit the class object, and I think super works only if class object is inherited. (New style class)

Now if I make animal also not inherit class object, I get an error. What is going on here?


Solution

  • It works that way because only one of the classes or inherited classes needs to inherit from object in order for your class to be created by the metaclass that object uses. The metaclass controls this MRO behavior.

    Here is one of the better answers on stack overflow explaining metaclasses.

    In python 3, this is all moot, since everything is a new-style class. Also, there's really no reason NOT to inherit from object, so unless you're forced to use some old library with classes that don't inherit from object, you might as well have all your classes inherit from it.