相关疑难解决方法(0)

Python装饰器作为静态方法

我正在尝试编写一个python类,它使用需要实例状态信息的装饰器函数.这是按预期工作,但如果我明确地使装饰器成为静态调试,我会收到以下错误:

Traceback (most recent call last):
  File "tford.py", line 1, in <module>
    class TFord(object):
  File "tford.py", line 14, in TFord
    @ensure_black
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)

为什么?

这是代码:

class TFord(object):
    def __init__(self, color):
        self.color = color

    @staticmethod
    def ensure_black(func):
        def _aux(self, *args, **kwargs):
            if self.color == 'black':
                return func(*args, **kwargs)
            else:
                return None
        return _aux

    @ensure_black
    def get():
        return 'Here is your shiny new T-Ford'

if __name__ == '__main__':
    ford_red = TFord('red')
    ford_black = TFord('black')

    print ford_red.get()
    print ford_black.get() …
Run Code Online (Sandbox Code Playgroud)

python static-methods decorator

43
推荐指数
2
解决办法
2万
查看次数

标签 统计

decorator ×1

python ×1

static-methods ×1