【发布时间】:2012-02-21 21:08:40
【问题描述】:
我正在尝试在新样式类中拦截对 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
如果我在列表周围使用该代理对象,我会得到非魔法方法的预期行为,但我的包装函数永远不会为魔法方法调用。
>>> 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
如果我不从对象继承(第一行 class ShowMeList:),一切都会按预期工作:
>>> l = ShowMeList(range(8))
>>> l #call to __repr__
before the call
after the call
[0, 1, 2, 3, 4, 5, 6, 7]
>>> l.append(9)
before the call
after the call
>> len(l._data)
9
如何使用新的样式类完成这种拦截?
【问题讨论】:
-
拦截双下划线方法的真正目的是什么?还是只是为了好奇?
-
我总是在此处保留所有魔法方法的列表:github.com/niccokunzmann/wwp/blob/…(已生成。因此适用于 python 2 和 3)
-
实际上,您似乎想要做的是拦截对新样式类的 instances 的魔术方法的调用 - 但是恕我直言,这仍然是一个好问题。跨度>
标签: python python-3.x