如何捕获在python中的对象上调用的任何方法? - python

我正在寻找有关如何存储在对象内部的对象上调用的方法的pythonic解决方案。

因为在python中,如果我想捕获例如abs()方法,我将像这样重载该运算符:

Catcher(object):
    def __abs__(self):
        self.function = abs

c = Catcher()
abs(c)  # Now c.function stores 'abs' as it was called on c

如果我想捕获一个具有其他属性的函数,例如pow(),我将使用此函数:

Catcher(object):
    def __pow__(self, value):
        self.function = pow
        self.value = value

c = Catcher()
c ** 2  # Now c.function stores 'pow', and c.value stores '2'

现在,我正在寻找一种通用的解决方案,以捕获和存储在Catcher上调用的任何类型的函数,而无需实现所有重载和其他情况。如您所见,我还想存储方法的属性值(如果有多个,则可以在列表中?)。

提前致谢!

python大神给出的解决方案

元类在这里无济于事。尽管将在当前对象的类型上查找特殊方法(因此,实例的类),但在执行此操作时未参考__getattribute____getattr__(可能是因为它们本身是特殊方法)。因此,要捕获所有dunder方法,您必须全部创建它们。

您可以通过列举__pow__ module来获得所有操作员特殊方法(__gt__operator等)的相当不错的列表:

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__,我们仍然会迷上它。

Python sqlite3数据库已锁定 - python

我在Windows上使用Python 3和sqlite3。我正在开发一个使用数据库存储联系人的小型应用程序。我注意到,如果应用程序被强制关闭(通过错误或通过任务管理器结束),则会收到sqlite3错误(sqlite3.OperationalError:数据库已锁定)。我想这是因为在应用程序关闭之前,我没有正确关闭数据库连接。我已经试过了: connectio…

Python pytz时区函数返回的时区为9分钟 - python

由于某些原因,我无法从以下代码中找出原因:>>> from pytz import timezone >>> timezone('America/Chicago') 我得到:<DstTzInfo 'America/Chicago' LMT-1 day, 18:09:00 STD…

用大写字母拆分字符串,但忽略AAA Python Regex - python

我的正则表达式:vendor = "MyNameIsJoe. I'mWorkerInAAAinc." ven = re.split(r'(?<=[a-z])[A-Z]|[A-Z](?=[a-z])', vendor) 以大写字母分割字符串,例如:'我的名字是乔。 I'mWorkerInAAAinc”变成…

如何检查变量是否是python中的特定类? - python

我有一个变量“ myvar”,当我打印出它时type(myvar)输出为:<class 'my.object.kind'> 如果我有10个变量的列表,包括此类字符串和变量..如何构造if语句来检查列表“ mylist”中的对象是否为<type 'my.object.kind'>? python大…

如何打印浮点数的全精度[Python] - python

我编写了以下函数,其中传递了x,y的值:def check(x, y): print(type(x)) print(type(y)) print(x) print(y) if x == y: print "Yes" 现在当我打电话check(1.00000000000000001, 1.0000000000000002)它正在打印:<…