gpt4 book ai didi

python - 在函数上定义 __getattr__ 和 __getitem__ 无效

转载 作者:太空狗 更新时间:2023-10-29 21:35:12 25 4
gpt4 key购买 nike

免责声明 这只是一个元编程练习,没有任何实际意义目的。

我已经在函数对象上分配了 __getitem____getattr__ 方法,但是没有效果...

def foo():
print "foo!"

foo.__getitem__ = lambda name: name
foo.__getattr__ = lambda name: name
foo.baz = 'baz'

健全性检查我们可以将属性分配给函数:

>>> foo.baz
'baz'

整洁。 “魔术 setter/getter ”怎么样?

>>> foo.bar
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'bar'

>>> foo['foo']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'function' object is not subscriptable

>>> getattr(foo, 'bar')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'bar'

是否可以在函数对象上使用“魔法 setter/getter ”?

最佳答案

不!将 __getitem__ 分配给实例不适用于任何类型的对象:

>>> class A(object):
... pass
...
>>> a = A()
>>> a.__getattr__ = lambda name: name
>>> a.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'A' object has no attribute 'foo'

并且您不能在内置函数类型上定义__getattr__:

>>> import types
>>> types.FunctionType.__getitem__ = lambda name: name
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can't set attributes of built-in/extension type 'function'

并且您不能继承types.FunctionType:

>>> import types
>>> class F(types.FunctionType):
... pass
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Error when calling the metaclass bases
type 'function' is not an acceptable base type

关于python - 在函数上定义 __getattr__ 和 __getitem__ 无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10803384/

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