元类在这里没有帮助;尽管在当前对象的类型上查找了特殊的方法(所以类为实例),但这样做时可能不会查询__getattribute__
或__getattr__
(可能是因为它们本身就是特殊方法)。所以要赶上全部 dunder方法,你不得不创建它们全部。
您可以通过枚举operator
module得到所有操作特殊的方法相当不错的列表(__pow__
,__gt__
等):
import operator
operator_hooks = [name for name in dir(operator) if name.startswith('__') and name.endswith('__')]
武装与列表中的类装饰可能是:
def instrument_operator_hooks(cls):
def add_hook(name):
operator_func = getattr(operator, name.strip('_'), None)
existing = getattr(cls, name, None)
def op_hook(self, *args, **kw):
print "Hooking into {}".format(name)
self._function = operator_func
self._params = (args, kw)
if existing is not None:
return existing(self, *args, **kw)
raise AttributeError(name)
try:
setattr(cls, name, op_hook)
except (AttributeError, TypeError):
pass # skip __name__ and __doc__ and the like
for hook_name in operator_hooks:
add_hook(hook_name)
return cls
然后应用,为您的类:
@instrument_operator_hooks
class CatchAll(object):
pass
演示:
>>> c = CatchAll()
>>> c ** 2
Hooking into __pow__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 11, in op_hook
AttributeError: __pow__
>>> c._function
<built-in function pow>
>>> c._params
((2,), {})
所以,尽管我们班没有定义__pow__
明确,我们还是迷上了进去。
那些不委托给dunder方法的函数呢? – delnan 2013-05-04 08:28:02
你可能想看看类装饰器和元类。 – 2013-05-04 08:37:09
@delnan我想,这些也是可以的,因为在我的情况下,这些函数正在寻找别的东西,一个值或一个方法来调用。 – 2013-05-04 08:37:49