小编Wal*_*llE的帖子

Python:记录所有类的方法而不修饰每个方法

我想在某些类中记录每个方法调用.我本可以做到的

class Class1(object):
    @log
    def method1(self, *args):
        ...
    @log
    def method2(self, *args):
        ...
Run Code Online (Sandbox Code Playgroud)

但是我在每个班级都有很多方法,而且我不想单独装饰每一个.目前,我尝试使用带有元类的hack(覆盖我记录的类',__getattribute__这样如果我尝试获取方法,它将返回一个日志记录方法):

class LoggedMeta(type):
    def __new__(cls, name, bases, attrs):
        def __getattribute__(self, name_):
            attr = super().__getattribute__(name_)
            if isinstance(attr, (types.MethodType, types.FunctionType)) and not name_.startswith("__"):
                return makeLogged(attr) #This returns a method that first logs the method call, and then calls the original method.
            return attr
        attrs["__getattribute__"] = __getattribute__
    return type.__new__(cls, name, bases, attrs)

class Class1(object):
    __metaclass__ = LoggedMeta
    def method1(self, *args):
        ...
Run Code Online (Sandbox Code Playgroud)

但是,我使用的是Python 2.X,而super()语法不起作用.当我调用super时,我没有__getattribute__类(但我确实有它的类名),所以我不能使用旧的超级语法super(Class, Inst). …

python logging class

5
推荐指数
2
解决办法
1425
查看次数

标签 统计

class ×1

logging ×1

python ×1