有没有办法确定调用类方法的顺序?

时间:2015-02-19 08:49:13

标签: python python-2.7 python-2.x

拥有20个以未知顺序调用的方法的类是否可以确定最后调用哪个方法? 我知道我可以在每个中添加一些print并由我自己确定。

但是有一些内置插件吗? 类似dis但显示方法名称

1 个答案:

答案 0 :(得分:2)

一种简单的方法是覆盖__getattribute__并检查所请求的属性是否是可调用的,如果是,则将其名称保存在某处:

class A(object):
    def __init__(self):
        self._last_called = None

    def method1(self):
        pass

    def method2(self):
        pass

    def __getattribute__(self, attr):
        val = object.__getattribute__(self, attr)
        if callable(val):
            self._last_called = attr
        return val

<强>演示:

>>> a = A()
>>> a._last_called
>>> a.method1()
>>> a._last_called
'method1'
>>> a.method2()
>>> a._last_called
'method2'

如果您不想修改实际的类,可以创建一个装饰器,然后将其应用于任何类:

def save_last_called_method(cls):
    original_getattribute = cls.__getattribute__

    def new_getattribute(ins, attr):
        val = original_getattribute(ins, attr)
        if callable(val):
            ins._last_called = attr
        return val

    cls.__getattribute__ = new_getattribute

    return cls

@save_last_called_method
class A(object):

    def method1(self):
        pass

    def method2(self):
        pass


@save_last_called_method
class B(object):

    def method3(self):
        pass

a = A()
a.method1()
print a._last_called
a.method2()
print a._last_called
b = B()
b.method3()
print b._last_called
print a._last_called

<强>输出:

method1
method2
method3
相关问题