Search code examples
pythonclassinheritanceattributessuper

Why my python subclass doesn't recognize attribute from super class?


I was testing inheritance of python, I've got this:

__metaclass__=type
class b:
    def __init__(s):
        s.hungry=True
    def eat(s):
        if(s.hungry):
            print "I'm hungry"
        else:
            print "I'm not hungry"
class d(b):
    def __init__(s):
        super(b,s).__init__()
    def __mysec__(s):
        print "secret!"

obj=d()
obj.eat()

There's runtime error as:

Traceback (most recent call last):
  File "2.py", line 17, in ?
    obj.eat()
  File "2.py", line 6, in eat
    if(s.hungry):
AttributeError: 'd' object has no attribute 'hungry'

I couldn't understand this, as the super class of "b" has s.hungry in its init, and the sub class calls "super" inside its own "init" Why still, python says "d" object has not attribute 'hungry'?

Another confusion: the error message treats "d" as an object, but I defined it as a class! Did I get anything wrong, how to make it work?


Solution

  • class d(b):
        def __init__(s):
            super(d,s).__init__()
        def __mysec__(s):
            print ("secret!")
    

    Document:

    For both use cases, a typical superclass call looks like this:

    > class C(B):
    >     def method(self, arg):
    >         super(C, self).method(arg)