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

Question:

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?

Asked By: Troskyvs

||

Answers:

I guess this is what you were looking for:

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

obj=d()
obj.eat()
Answered By: Hisagr
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)
Answered By: 宏杰李

I prefer to write the code for more clarity in python 3.x

class Base:
    def __init__(self):
        self.hungry=True

    def eat(self):
        if(self.hungry):
            print("I'm hungry")
        else:
            print("I'm not hungry")

class Derived(Base):
    def __init__(self):
        super().__init__() # this works
        # super(Derived,self).__init__() # this works
        # super(Base,self).__init__() # this doesn't work

>>> d=Derived()
>>> d.eat()
I'm hungry
Answered By: Andrea