【问题标题】:Add a method to classes with a decorator使用装饰器向类添加方法
【发布时间】:2015-01-11 16:42:37
【问题描述】:

如何在 Python 中使用装饰器向类添加方法?我的目标是让使用我的装饰器的类有一个可用的方法。

这是一个简化的例子。我要instance.dec_added_func() 回复'X'

>>> def myFunction():
...   return 'X'
... 
>>> myFunction()
'X'
>>> def myDecorator(cls):
...   cls.dec_added_func = myFunction
... 
>>> @myDecorator
... class MyClass(object):
...   a = 'A'
... 
>>> instance = MyClass()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'NoneType' object is not callable

我知道这可以通过继承基类来实现,但我希望能够使用装饰器来实现。

【问题讨论】:

  • 装饰器函数需要返回它所传递的类。

标签: python class decorator


【解决方案1】:

你需要做两件事:

  1. myDecorator返回它传递的类对象:

    def myDecorator(cls):
        cls.dec_added_func = myFunction
        return cls
    

    否则,装饰器将默认返回None,而当您尝试调用MyClass() 时,您将获得TypeError 以尝试调用None

  2. 使myFunction 接受self 参数:

    def myFunction(self):
        return 'X'
    

    每当你在你的类的实例上调用它时,它都会被隐式传递。

下面是一个演示:

>>> def myFunction(self):
...     return 'X'
...
>>> def myDecorator(cls):
...     cls.dec_added_func = myFunction
...     return cls
...
>>> @myDecorator
... class MyClass(object):
...     a = 'A'
...
>>> instance = MyClass()
>>> instance.dec_added_func()
'X'
>>>

【讨论】:

    【解决方案2】:

    对于一个简短的方法,如果您认为它更具可读性,您也可以考虑使用 lambda:

    def myDecorator(cls):
        cls.dec_added_func = lambda self: 'X'
        return cls
    

    另一个将== 运算符添加到具有value 字段的类的示例:

    def equals(cls):
        cls.__eq__ = lambda self, other: self.value == other.value
        return cls
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-10-13
      • 1970-01-01
      • 1970-01-01
      • 2014-01-14
      • 1970-01-01
      • 2020-01-11
      • 1970-01-01
      相关资源
      最近更新 更多