【发布时间】:2016-03-05 09:34:22
【问题描述】:
class One:
i = One.get(9)
@staticmethod
def get(val):
pass
我尝试使用静态方法初始化静态变量,但是上面的代码引发了这个错误:
NameError: name 'One' is not defined
如何在 Python 中使用静态方法初始化静态变量?
【问题讨论】:
class One:
i = One.get(9)
@staticmethod
def get(val):
pass
我尝试使用静态方法初始化静态变量,但是上面的代码引发了这个错误:
NameError: name 'One' is not defined
如何在 Python 中使用静态方法初始化静态变量?
【问题讨论】:
class One:
@staticmethod
def get(val):
pass
i = get.__func__(9)
虽然可能不是最 Pythonic 的方式。注意i 变量在get 的声明之后。由于@staticmethod 不能直接调用(如果这样做,您会收到一条消息),因此您必须改为执行底层函数(__func__)。
【讨论】: