在函数上定义__getattr__和__getitem__无效 [英] Defining __getattr__ and __getitem__ on a function has no effect

查看:74
本文介绍了在函数上定义__getattr__和__getitem__无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

免责声明这只是元编程中的一种练习,没有实际意义 目的.

Disclaimer This is just an exercise in meta-programming, it has no practical purpose.

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

I've assigned __getitem__ and __getattr__ methods on a function object, but there is no effect...

def foo():
  print "foo!"

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

我们可以进行 赋值给功能的健全性检查:

Sanity check that we can assign properties to a function:

>>> foo.baz
'baz'

整洁. 魔术吸气剂"怎么样?

Neat. How about the "magic getters"?

>>> 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'

是否可以在功能对象上使用魔术吸气剂"?

Is it possible to have a "magic getter" on a function object?

推荐答案

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

Nope! Assigning __getitem__ to an instance doesn't work on any type of object:

>>> 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__:

And you can't define __getattr__ on the built-in function type:

>>> 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

这篇关于在函数上定义__getattr__和__getitem__无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆