微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

为什么这个类装饰器不装饰?

如何解决为什么这个类装饰器不装饰?

这里有点失落。我试图装饰一个类的所有方法,并使用解决方here。我觉得我已经有了所有的部分(见下文),但是当我初始化类/调用它的方法时,什么也没有发生。

举个例子,我有函数装饰器

def my_decorator(func):
    def wrapper(*args):
        print("Something is happening before the function is called.")
        return func(*args)
        print("Something is happening after the function is called.")
    return wrapper

和类装饰器

def for_all_methods(decorator):
    import inspect
    def decorate(cls):
        for name,fn in inspect.getmembers(cls,inspect.ismethod):
            print(name,fn)
            setattr(cls,name,decorator(fn))
        return cls
    return decorate

和玩具课

@for_all_methods(my_decorator)
class Car:
    def __init__(self):
        self.wheels = 4
        self.price=20000
        self.mileage = 0
    
    def drive(self,miles):
        self.mileage += miles
    
    def depreciate(self):
        self.price-=0.1*self.mileage

然而当我初始化类时

c = Car()

或者调用它的方法,它们没有被修饰。是什么赋予了?我觉得我一定错过了一些微不足道的东西。

解决方法

inspect.ismethod 检查绑定方法对象 - 您从 Car().drive 获得的东西,而不是 Car.driveCar.drive 是一个函数对象。

您正在查看的代码仅针对 Python 2 编写。方法在 Python 2 上的工作方式略有不同。

,

好的,如果我将 inspect.ismethod 更改为 inspect.isfunction,它会起作用。

我仍然没有 100% 理解它,因为

for name,fn in inspect.getmembers(Car(),inspect.ismethod):
     print(name,fn)

印刷品

__init__ <bound method my_decorator.<locals>.wrapper of <__main__.Car object at 0x7fb577e30cf8>>
depreciate <bound method my_decorator.<locals>.wrapper of <__main__.Car object at 0x7fb577e30cf8>>
drive <bound method my_decorator.<locals>.wrapper of <__main__.Car object at 0x7fb577e30cf8>>

正如我所料。

编辑:user2357112 支持莫妮卡澄清 here

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。