使用python的super()继承属性

2024-09-28 03:13:58 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 2.7.10

我只想继承super-class属性,这是一个标准的面向对象的东西。在

从我在这里和其他地方的网上资料来看,这应该是有效的:

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

得到:

^{pr2}$

那怎么不是一种类型?我强调这个问题:

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

我真想不起那件事。对象实例不是其类类型的实例吗?怎么可能呢?在

任何帮助将不胜感激。在


Tags: 实例selfobj类型标准属性initdef
1条回答
网友
1楼 · 发布于 2024-09-28 03:13:58

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

如果超类声明为

class Foo:
   ...

您将看到错误,因为创建的类是一个旧的0style类,它不支持super

超类声明必须是

^{pr2}$

例如:

>>> 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中,旧样式的类已被删除,因此不再需要从对象显式继承。在

相关问题 更多 >

    热门问题