Python3:检查方法是否静态 [英] Python3: check if method is static
问题描述
Simmilar问题(与Python2相关: Python:检查方法是否静态)
Simmilar question (related with Python2: Python: check if method is static)
让我们考虑以下类定义:
Lets concider following class definition:
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
在Python 3中,不再有instancemethod
,一切都正常了,因此与Python 2相关的答案将不再起作用.
In Python 3 there is no instancemethod
anymore, everything is function, so the answer related to Python 2 will not work anymore.
正如我所说的,一切都是函数,因此我们可以调用A.f(0)
,但是我们当然不能调用A.f()
(参数不匹配).但是,如果我们创建实例a=A()
并调用a.f()
,则Python将第一个参数传递给函数A.f
,self
.调用a.g()
会阻止发送它或捕获self
-因此必须有一种方法来测试它是否为静态方法.
As I told, everything is function, so we can call A.f(0)
, but of course we cannot call A.f()
(argument missmatch). But if we make an instance a=A()
and we call a.f()
Python passes to the function A.f
the self
as first argument. Calling a.g()
prevents from sending it or captures the self
- so there have to be a way to test if this is staticmethod or not.
那么我们可以在Python3中检查某个方法是否声明为static
吗?
So can we check in Python3 if a method was declared as static
or not?
推荐答案
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
print(type(A.__dict__['g']))
print(type(A.g))
<class 'staticmethod'>
<class 'function'>
这篇关于Python3:检查方法是否静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!