gpt4 book ai didi

python - super() 返回代理对象是什么意思?

转载 作者:行者123 更新时间:2023-12-05 01:06:03 25 4
gpt4 key购买 nike

根据documentation ,

Return a proxy object that delegates method calls to a parent or sibling class of type.

找到最接近我需要的答案 here :

Just like int() or str() or any of the other built-in types, the type of the object returned by calling super() is that type.

我的解释是,super() 返回一个指定类型的对象。但是,我不确定为什么使用“代理”一词,它是否与名为“代理”的设计模式有关?例如,

class Contact:
def __init__(self, phone, email):
self.phone = phone
self.email = email

class Friend(Contact):
def __init__(self, name, phone, email):
self.name = name
super().__init__(phone, email)

对于这种情况,就我而言, super().__init__(phone, email) 相当于使用 Contact.__init__(self, phone, email)。也就是说,Contact 的实例是从 super() 返回的,我们为其定义了一个新属性 name,但我不明白如何它与该设计模式有关。

最佳答案

That is, an instance of Contact is returned from super() for whichwe define a new attribute name

不,它没有。您可以通过查看 print(type(super())) 进行检查。 super() 返回 super 的一个实例... super 实际上是一个类!该对象充当代理,即它代理方法解析顺序中的下一个类的属性查找。以下是在纯 Python 中实现它的方法:

class SimpleSuper:
def __init__(self, cls, instance):
self.cls = cls
self.instance = instance
def __getattr__(self, name):
mro = type(self.instance).mro()
next_cls = mro[mro.index(self.cls) + 1]
attribute = getattr(next_cls, name)
if hasattr(attribute, "__get__"):
return attribute.__get__(self.instance, self.cls)
return attribute

关于python - super() 返回代理对象是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69907830/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com