【问题标题】:Using python's super() to inherit attributes [duplicate]使用python的super()继承属性[重复]
【发布时间】:2019-05-15 23:25:26
【问题描述】:

Python 2.7.10

嗨,

我想做的就是继承超类属性,这是一个标准的面向对象的事情。

从我可以在这里和其他地方在线找到的内容来看,这应该可以:

class SubClass(MyParentClass):
   def __init__(self):
      super(SubClass, self).__init__()

得到:

TypeError: must be type, not classobj

那怎么不是类型?我提出这个问题:

class SubClass(MyParentClass):
   def __init__(self):
      super(type(self.__class__), self).__init__()

得到:

TypeError: super(type, obj): obj must be an instance or subtype of type

我无法将我的大脑包裹在那个人身上。对象实例不是其类类型的实例吗?这怎么可能?

任何帮助将不胜感激。

【问题讨论】:

  • 这可能只是在 python 2.7 中的东西,因为它在 python 3.6 中对我来说很好。
  • 如果SubClass.__init__ 除了调用另一个__init__ 之外没有做任何其他事情,它可以完全省略。方法本身将被继承和调用。

标签: python inheritance attributes python-2.x super


【解决方案1】:

在 Python2 中,super 仅在类层次结构继承自 object 时才有效。

如果超类被声明为

class Foo:
   ...

你会看到你看到的错误,因为创建的类是一个不支持super的old0style类

超类声明需要是

class Foo(object):
    ....

例如:

>>> class Foo:pass
... 
>>> class Bar(Foo):
...     def __init__(self):
...         super(Bar, self).__init__()
... 
>>> b = Bar()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 3, in __init__
TypeError: super() argument 1 must be type, not classobj

在 Python3 中,旧式类已被删除,因此不再需要从对象显式继承。

【讨论】:

  • "class Foo(object):" 做到了。谢谢snakecharmerb。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 2017-10-30
  • 2017-10-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多