【发布时间】:2011-09-18 17:19:12
【问题描述】:
我正在尝试编写一个 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
为什么?
代码如下:
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 作为第一个参数吗?
【问题讨论】:
-
为什么你认为你需要
@staticmethod?很明显,你不明白这意味着什么。静态方法未绑定到对象的实例,因此它们没有self参数(并且无法访问实例变量)。 -
@Nick:装饰器
ensure_black不需要访问self。它只需要访问func。 -
@Sven: 好点子 - 我被
def get()也没有使用self的脸吓到了,所以对_aux怎么可能感到困惑。 -
你能看看stackoverflow.com/questions/51260036/… 并发布你是如何在没有构造函数的情况下使它工作的吗?
标签: python decorator static-methods