我正在尝试编写一个python类,该类使用需要实例状态信息的decorator函数。这是按预期工作的,但是如果我显式地将decorator设为staticmetod,则会得到以下错误:Traceback (most recent call last):
File "tford.py", line 1, in
class TFord(object):
File "tford.py", line 14, in TFord
@ensure_black
TypeError: 'staticmethod' object is not callable
为什么?
代码如下: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()
如果我只删除@staticmethod行,一切都正常,但我不明白为什么。它不需要self作为第一个参数吗?