gpt4 book ai didi

python - 为什么人们在 __get__ 中将 owner 参数默认为 None?

转载 作者:太空狗 更新时间:2023-10-29 20:18:26 26 4
gpt4 key购买 nike

我经常看到这个:

def __get__(self, instance, owner=None):

为什么有些人对 owner 参数使用默认值 None

这甚至在 Python docs 中完成:

descr.__get__(self, obj, type=None) --> value

最佳答案

因为所有者可以很容易地从实例中派生出来,所以第二个参数是可选的。只有当没有从中派生所有者的实例时,才需要所有者参数。

这在引入描述符的提案中有描述,PEP 252 - Making Types Look More Like Classes :

__get__: a function callable with one or two arguments thatretrieves the attribute value from an object. This is alsoreferred to as a "binding" operation, because it may return a"bound method" object in the case of method descriptors. Thefirst argument, X, is the object from which the attribute mustbe retrieved or to which it must be bound. When X is None,the optional second argument, T, should be meta-object and thebinding operation may return an unbound method restricted toinstances of T.

(大胆强调我的)

从第一天开始,绑定(bind)就意味着仅适用于实例,类型是可选的。例如,方法不需要它,因为它们可以单独绑定(bind)到实例:

>>> class Foo: pass
...
>>> def bar(self): return self
...
>>> foo = Foo()
>>> foo.bar = bar.__get__(foo) # look ma! no class!
>>> foo.bar
<bound method Foo.bar of <__main__.Foo object at 0x10a0c2710>>
>>> foo.bar()
<__main__.Foo object at 0x10a0c2710>

此外,第二个参数可以很容易地从第一个参数派生;见证一个 classmethod 仍然绑定(bind)到类,即使我们没有传递一个:

>>> classmethod(bar).__get__(foo)
<bound method type.bar of <class '__main__.Foo'>>
>>> classmethod(bar).__get__(foo)()
<class '__main__.Foo'>

参数首先存在的唯一原因是支持绑定(bind)到类,例如当没有要绑定(bind)的实例时。又是类方法;绑定(bind)到 None 作为实例是行不通的,它只有在我们实际传入类时才有效:

>>> classmethod(bar).__get__(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __get__(None, None) is invalid
>>> classmethod(bar).__get__(None, Foo)
<bound method type.bar of <class '__main__.Foo'>>

关于python - 为什么人们在 __get__ 中将 owner 参数默认为 None?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31626653/

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