相关疑难解决方法(0)

如何在新样式类中拦截对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)

python python-3.x

32
推荐指数
2
解决办法
5901
查看次数

标签 统计

python ×1

python-3.x ×1