Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用python';s super()来继承属性_Python_Inheritance_Attributes_Python 2.x_Super - Fatal编程技术网

使用python';s super()来继承属性

使用python';s super()来继承属性,python,inheritance,attributes,python-2.x,super,Python,Inheritance,Attributes,Python 2.x,Super,Python 2.7.10 嗨 我所要做的就是继承超类属性,这是一个标准的面向对象的东西 从我在这里和其他地方的在线信息来看,这应该是可行的: class SubClass(MyParentClass): def __init__(self): super(SubClass, self).__init__() 这就得到: TypeError: must be type, not classobj TypeError: super(type, obj): obj must b

Python 2.7.10

我所要做的就是继承超类属性,这是一个标准的面向对象的东西

从我在这里和其他地方的在线信息来看,这应该是可行的:

class SubClass(MyParentClass):
   def __init__(self):
      super(SubClass, self).__init__()
这就得到:

TypeError: must be type, not classobj
TypeError: super(type, obj): obj must be an instance or subtype of type
那怎么不是一种类型?我以下列方式提出这一问题:

class SubClass(MyParentClass):
   def __init__(self):
      super(type(self.__class__), self).__init__()
这就得到:

TypeError: must be type, not classobj
TypeError: super(type, obj): obj must be an instance or subtype of type
我不能把我的脑子放在那个上面。对象实例不是其类类型的实例?这怎么可能呢


任何帮助都将不胜感激

在Python2中,
super
仅当类层次结构继承自
对象时才起作用

如果超类声明为

class Foo:
   ...
您将看到错误,因为创建的类是一个旧的0样式的类,不支持
super

需要修改超类声明

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
>类Foo:pass
... 
>>>分类栏(Foo):
...     定义初始化(自):
...         超级(棒,自我)。\uuuu初始化
... 
>>>b=巴()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第3行,在_init中__
TypeError:super()参数1必须是类型,而不是classobj

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

这可能只是python 2.7中的一种情况,因为它在python 3.6中工作得很好。如果
子类.\uuuuu init\uuuuu
除了调用另一个
\uuu init\uuuu
之外,它不做任何其他事情,则可以完全忽略。该方法本身将被继承并调用。谢谢你,蛇魔法师。