当我尝试在类体中使用静态方法,并使用内置的staticmethod
函数作为装饰器来定义静态方法时,如下所示:
class Klass(object):
@staticmethod # use as decorator
def _stat_func():
return 42
_ANS = _stat_func() # call the staticmethod
def method(self):
ret = Klass._stat_func() + Klass._ANS
return ret
我得到以下错误:
Traceback (most recent call last):
File "call_staticmethod.py", line 1, in <module>
class Klass(object):
File "call_staticmethod.py", line 7, in Klass
_ANS = _stat_func()
TypeError: 'staticmethod' object is not callable
我理解为什么会发生这种情况(描述符绑定),并可以通过在上次使用后手动将_stat_func()
转换为静态方法来解决它,如下所示:
class Klass(object):
def _stat_func():
return 42
_ANS = _stat_func() # use the non-staticmethod version
_stat_func = staticmethod(_stat_func) # convert function to a static method
def method(self):
ret = Klass._stat_func() + Klass._ANS
return ret
所以我的问题是:
有没有更干净的或者更“Pythonic式”的方法来实现这一点?
发布于 2012-10-04 07:24:28
staticmethod
对象显然有一个存储原始原始函数的__func__
属性(有必要这样做)。所以这将会起作用:
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
_ANS = stat_func.__func__() # call the staticmethod
def method(self):
ret = Klass.stat_func()
return ret
顺便说一句,尽管我怀疑staticmethod对象具有某种存储原始函数的属性,但我对细节一无所知。本着教人钓鱼而不是给他们鱼的精神,以下是我所做的调查并找出答案(来自我的Python会话的C&P ):
>>> class Foo(object):
... @staticmethod
... def foo():
... return 3
... global z
... z = foo
>>> z
<staticmethod object at 0x0000000002E40558>
>>> Foo.foo
<function foo at 0x0000000002E3CBA8>
>>> dir(z)
['__class__', '__delattr__', '__doc__', '__format__', '__func__', '__get__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']
>>> z.__func__
<function foo at 0x0000000002E3CBA8>
在交互式会话中进行类似的挖掘(dir
非常有用)通常可以非常快速地解决这类问题。
发布于 2014-12-11 00:42:27
这是我喜欢的方式:
class Klass(object):
@staticmethod
def stat_func():
return 42
_ANS = stat_func.__func__()
def method(self):
return self.__class__.stat_func() + self.__class__._ANS
由于DRY principle,我更喜欢这种解决方案而不是Klass.stat_func
。让我想起了Python3中的reason why there is a new super()
:)
但我同意其他人的观点,通常最好的选择是定义一个模块级函数。
例如,对于@staticmethod
函数,递归可能看起来不是很好(您需要通过在Klass.stat_func
中调用Klass.stat_func
来打破DRY原则)。这是因为在静态方法中没有对self
的引用。有了模块级函数,一切看起来都没问题。
发布于 2012-10-04 07:21:05
在类定义之后注入class属性怎么样?
class Klass(object):
@staticmethod # use as decorator
def stat_func():
return 42
def method(self):
ret = Klass.stat_func()
return ret
Klass._ANS = Klass.stat_func() # inject the class attribute with static method value
https://stackoverflow.com/questions/12718187
复制相似问题