简体   繁体   中英

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?

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()
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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM