python如何从类主体内部调用静态方法 [英] python how to call static method from inside of a class body
问题描述
假设我有一个带有静态方法的类,并且希望将一个类属性设置为该方法返回的值:
A类:
@静态方法
def foo():
返回12
baz = foo()
但是这样做会出错:
Traceback(最近一次呼叫最近):
文件< stdin>,在< module>中的第1行。
文件< stdin>,A
TypeError中的第5行:'staticmethod'对象不可调用
我找到了解决此问题的方法:
class A:
类B:
@staticmethod
def foo():
return 2
baz = B.foo()
但是例如,如果我写:
A类:
类B:
@静态方法
def foo():
返回2
类C:
baz = B.foo()
我也遇到错误:
跟踪(最近一次通话最近):
文件< stdin>,在< module>中的第1行。
文件< stdin>,在A中的第6行
文件< stdin>,在C中的第7行,
NameError:名称'B'未定义
有没有一种方法可以在声明时从类内部调用静态方法?
为什么第1和第3个代码示例不起作用,但是第2个示例起作用? python解释器如何处理此类声明?
静态方法
是描述符。描述符公开了 __ get __(instance,cls)
方法,从而可以通过实例或在类级别对其进行访问。
现在,您要在一个类节中调用它。通常,这将是不可能的,因为实例和类都不可用。但是静态方法
在任何情况下都会忽略这两种方法,因此您可以使用以下相当讨厌的方法来调用它。
A类:
@staticmethod
def foo():
返回12
baz = foo .__ get __(无对象) ()
然后
>>> A.baz
12
注意:通过 object
作为第二个参数是 staticmethod
坚持要通过某种类型的类作为第二个参数。 / p>
Let's assume I have a class, with a static method, and I want a class property to be set to the value that this method returns:
class A:
@staticmethod
def foo():
return 12
baz = foo()
But doing this I get an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in A
TypeError: 'staticmethod' object is not callable
I found a way to get around this:
class A:
class B:
@staticmethod
def foo():
return 2
baz = B.foo()
But for example if I write:
class A:
class B:
@staticmethod
def foo():
return 2
class C:
baz = B.foo()
I also get an error:
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
Is there a way to call static methods from within a class while declaring it? Why 1st and 3rd examples of code does not work but 2nd does? How python interpretor handles such declarations?
The staticmethod
is a descriptor. A descriptor exposes the __get__(instance, cls)
method allowing it to be accessed either through an instance or at the class level.
Now in your case you wish to call it within a class stanza. Normally this would not be possible as neither an instance nor the class are yet available. However a staticmethod
ignores both in any case so you can use the following rather nasty approach to call it.
class A:
@staticmethod
def foo():
return 12
baz = foo.__get__(None, object)()
Then
>>> A.baz
12
Note: The only reason to pass object
as the second argument is that staticmethod
insists on being passed a class of some kind as the second argument.
这篇关于python如何从类主体内部调用静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!