gpt4 book ai didi

python - 在 __func__ 上设置属性

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

在实例方法的文档中指出:

Methods also support accessing (but not setting) the arbitrary function attributes on the underlying function object.

但我似乎无法验证该限制。我尝试设置任意值和函数的“特殊属性”之一:

class cls:
def foo(self):
f = self.foo.__func__
f.a = "some value" # arbitrary value
f.__doc__ = "Documentation"
print(f.a, f.__doc__)

执行时,不会产生任何错误,并且输出符合预期:

cls().foo() # prints out f.a, f.__doc__

我对文档的误解是什么?

最佳答案

您误解了所说的内容。它表示您可以从方法访问底层函数对象的属性,但不能设置属性!

>>> class Foo:
... def foo(self):
... self.foo.__func__.a = 1
... print(self.foo.a)
... self.foo.a = 2
...
>>> Foo().foo()
1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in foo
AttributeError: 'method' object has no attribute 'a'

注意如何foo.a当您将其设置为 __func__ 时会更新值,但不能直接使用 self.foo.a = value 设置它.

因此函数对象可以随意修改,方法wrapper仅提供对底层函数属性的只读访问。

关于python - 在 __func__ 上设置属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40528867/

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