假设我有一个类,它有一个静态方法,我想一个类属性被设置为值,这个方法返回:蟒蛇如何从类主体的内部调用静态方法
class A:
@staticmethod
def foo():
return 12
baz = foo()
但这样做,我得到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in A
TypeError: 'staticmethod' object is not callable
我找到了一种方法来解决这个问题:
class A:
class B:
@staticmethod
def foo():
return 2
baz = B.foo()
但EXA mple如果我写:
class A:
class B:
@staticmethod
def foo():
return 2
class C:
baz = B.foo()
我也得到一个错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 6, in A
File "<stdin>", line 7, in C
NameError: name 'B' is not defined
有没有一种方法调用类内的静态方法,同时宣布呢? 为什么代码的第一和第三个例子不起作用,但第二个例子呢? python解释器如何处理这种声明?