Woj*_*ilo 6 python static static-methods introspection python-3.x
Simmilar问题(与Python2相关:Python:检查方法是否为静态)
让concider遵循类定义:
class A:
def f(self):
return 'this is f'
@staticmethod
def g():
return 'this is g'
Run Code Online (Sandbox Code Playgroud)
在Python 3中已经没有instancemethod了,一切都是函数,因此与Python 2相关的答案将不再适用.
正如我所说,一切都是功能,所以我们可以打电话A.f(0),但我们当然不能打电话A.f()(参数不匹配).但是,如果我们做一个实例a=A(),我们叫a.f()Python的传递给函数A.f的self作为第一个参数.调用a.g()阻止发送或捕获self- 所以必须有一种方法来测试这是否是静态方法.
那么我们可以检查Python3是否声明了方法static?
roo*_*oot 10
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'>
Run Code Online (Sandbox Code Playgroud)
对于 Python 3.2 或更高版本,用于inspect.getattr_static()检索属性而不调用描述符协议:
通过描述符协议检索属性而不触发动态查找,
__getattr__()或__getattribute__().
使用isinstance(..., staticmethod)结果:
>>> from inspect import getattr_static
>>> isinstance(getattr_static(A, 'g'), staticmethod)
True
Run Code Online (Sandbox Code Playgroud)
该函数可以处理实例和类,并将为您扫描完整的类层次结构:
>>> class B(A): pass
...
>>> isinstance(getattr_static(B, 'g'), staticmethod) # inherited
True
>>> isinstance(getattr_static(B(), 'g'), staticmethod) # instance, inherited
True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1285 次 |
| 最近记录: |