为什么我的python子类不能识别超类的属性?

时间:2016-12-24 05:35:31

标签: python class inheritance attributes super

我正在测试python的继承,我有这个:

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

运行时错误为:

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'

我无法理解这一点,因为超级类“b”在其 init 中有s.hungry,而子类在其自己的“ init <内部调用”super“ / STRONG>” 为什么,python说“d”对象没有归因于“饥饿”?

另一个困惑:错误消息将“d”视为对象,但我将其定义为类! 我有什么不对的,如何让它发挥作用?

2 个答案:

答案 0 :(得分:2)

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

Document

  

对于这两种用例,典型的超类调用如下所示:

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

答案 1 :(得分:1)

我想这就是你要找的东西:

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