我已经读过可以在Python中向现有对象(即,不在类定义中)添加方法.
我知道这样做并不总是好事.但是人们怎么可能这样做呢?
我试图在新的样式类中拦截对python的双下划线魔术方法的调用.这是一个简单的例子,但它显示了意图:
class ShowMeList(object):
def __init__(self, it):
self._data = list(it)
def __getattr__(self, name):
attr = object.__getattribute__(self._data, name)
if callable(attr):
def wrapper(*a, **kw):
print "before the call"
result = attr(*a, **kw)
print "after the call"
return result
return wrapper
return attr
Run Code Online (Sandbox Code Playgroud)
如果我在列表周围使用该代理对象,我会获得非魔术方法的预期行为,但我的包装函数永远不会被魔术方法调用.
>>> l = ShowMeList(range(8))
>>> l #call to __repr__
<__main__.ShowMeList object at 0x9640eac>
>>> l.append(9)
before the call
after the call
>> len(l._data)
9
Run Code Online (Sandbox Code Playgroud)
如果我不从对象继承(第一行class ShowMeList:),一切都按预期工作:
>>> l = ShowMeList(range(8))
>>> l #call to __repr__
before the call …Run Code Online (Sandbox Code Playgroud)