假设我有一个带有静态方法的类,并且我希望将类属性设置为该方法返回的值:
class A:
@staticmethod
def foo():
return 12
baz = foo()
Run Code Online (Sandbox Code Playgroud)
但是这样做我得到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in A
TypeError: 'staticmethod' object is not callable
Run Code Online (Sandbox Code Playgroud)
我找到了解决这个问题的方法:
class A:
class B:
@staticmethod
def foo():
return 2
baz = B.foo()
Run Code Online (Sandbox Code Playgroud)
但例如,如果我写:
class A:
class B:
@staticmethod
def foo():
return 2
class C:
baz = B.foo()
Run Code Online (Sandbox Code Playgroud)
我也收到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in …Run Code Online (Sandbox Code Playgroud)