我一直在思考这个问题,希望这不是一个显而易见的答案我没有意识到的愚蠢问题:为什么我不能像 super()()
那样调用 super()
的 __init__
方法?而是必须像这样调用该方法:super().__init__()
以下是一个示例,在执行时会出现 TypeError: 'super' object is not callable
错误(具体是来自于__init__
的第3行的第6行):
class My_Int(int):
def __init__(self,value,extr_data=None):
super()(value)
self.extr_data=extr_data
x=My_Int(3)
super()
获取的是继承类,因此 super()(value)
与 int(value)
相同吗?
另外,为什么在从类 list
继承时不能使用 len
函数?难道 len()
不做与 __len__()
相同的事情吗?
class My_List(list):
def some_method1(self):
print(len(super()))
def some_method2(self):
print(super().__len__())
x=My_List((1,2,3,4))
x.some_method2()
x.some_method1()
这个示例会按照预期输出数字 4,然后输出一个错误。以下是输出的具体内容:
4
Traceback (most recent call last):
File "/home/user/test.py", line 11, in <module>
x.some_method1()
File "/home/user/test.py", line 3, in some_method1
print(len(super()))
TypeError: object of type 'super' has no len()
请注意,我在调用some_method1
之前先调用了some_method2
(不好意思刚刚有点混淆)。
这里是否有什么明显的遗漏吗?
- 附言:感谢所有的帮助!
int(value)
也不能达到您想要的效果。 - user2357112super()()
创建一个新的超类实例。super().__init__()
的目的是在当前实例上调用父类的init方法。 - Barmarsuper()()
会引发TypeError错误。 - user2357112super()
并不仅仅是一个代表实例本身转换为其父类的替身。len(super())
没有任何意义,因为super
对象完全是另一回事,负责导航给定其类的对象的方法解析顺序。在Python 2中,这更加明确,因为您必须像super(cls, self)
这样传递两个参数,但Python 3添加了语法糖,使这对于最“明显”的情况自动完成。 - Iguananaut__init__
不会创建新的实例,它只是在实例创建后初始化实例。这就是为什么__init__
会将self
作为参数传入的原因。self
已经是该类的一个实例了。那么self
从哪里来呢?(提示:请查看__new__
) - Iguananaut