【问题标题】:Why my python subclass doesn't recognize attribute from super class?为什么我的 python 子类不能识别超类的属性?
【发布时间】:2017-05-09 16:51:48
【问题描述】:

我正在测试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" 为什么仍然,python 说“d”对象没有属性“饥饿”?

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

【问题讨论】:

  • 在当前类上使用super,而不是父类。即super(d, s).__init__()
  • 另外,我强烈建议不要在 Python 中使用单字母名称。我建议阅读python.org/dev/peps/pep-0008
  • python3中的super()很简单,不需要传参数。
  • 一个类是一个对象,一个对象的类实例。你为什么要覆盖d 中的dunder init? - 删除它。

标签: python class inheritance attributes super


【解决方案1】:
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)

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2014-12-20
      • 2019-11-15
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      相关资源
      最近更新 更多