我已经读了the documentation for ^{
Return a proxy object that delegates method calls to a parent or sibling class of type. This is useful for accessing inherited methods that have been overridden in a class.
If the second argument is an object,
isinstance(obj, type)
must be true. If the second argument is a type,issubclass(type2, type)
must be true (this is useful for classmethods).
super(a,b)
是什么意思?在在^{
Typical implementations create a new instance of the class by invoking the superclass’s __new__() method using
super(currentclass, cls).__new__(cls[, ...])
with appropriate arguments and then modifying the newly-created instance as necessary before returning it.
super(currentclass, cls).__new__(cls[, ...])
如果currentclass
等于cls
,则有{
cls
的实例,以便在返回的对象上调用__init__
?在
你应该看一下雷蒙德·海丁格的《2015年PyCon》的演讲,Super is considered super!
但如果没有,为什么不加上一堆打印声明来回答你的问题呢?在
产生以下输出(附加注释):
^{pr2}$显然,
super
返回super
类型的类。根据文档,它是一个代理对象。根据定义,代理是对其他事物的替代。在本例中,代理是获取Mom
的替代品。您可以看到,当我们实际调用__init__
函数时,Mom的init函数被调用。在您会注意到,Dad的init函数没有被调用。这是因为,如果你看Raymond的演讲,你就会知道
super
从左到右寻找父函数。在你在这里看到同样的行为
如果你改变顺序,你会看到的:
总而言之:
代理是代表其他事物的东西。在我们的例子中,
super
是妈妈和爸爸的代理,这取决于它们继承的顺序。老实说,我找不到任何有意义的兄弟姐妹。我不知道你什么时候需要。
返回
super
的实例。只有当你有从
type
继承的东西,例如super(type, type)
时,这才真正有效,因为你需要一个该类型的实例。object
也可以工作,因为:打印(isinstance(object,object)) 打印(isinstance(type,type)) 打印(isinstance(对象,类型)) 打印(isinstance(type,object))
在这个过程中,有一些非常复杂的魔法。在
object.__new__
返回一些东西。我不确定该函数的实际源代码在哪里,或者如果您对确切的机制感兴趣,我可以告诉您。在“what does
super
return”的答案与“it return a list”或“it return a modified copy of The second object”不同。super
返回一个类型为super
的对象,该类型专门设计为具有文档所述的质量。在也许这将有助于展示
super
的纯Python实现。如果super
不是用C编写的,它基本上如下所示:现在您可以看到}不是类,则检查实例dict。在
super(a, b)
构造了一个super
对象,而super(a, b).whatever
调用了super
对象的__getattribute__
方法来搜索第二个参数的方法解析顺序,以找到我们想要的属性。b.whatever
的属性查找过程非常相似,只是没有切掉MRO的第一部分,如果{相关问题 更多 >
编程相关推荐