Python3:检查方法是否是静态的

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.fself作为第一个参数.调用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)

  • `A .__ dict __ ['g']`与`Ag`不同,因为函数是[descriptors](http://docs.python.org/2/reference/datamodel.html#descriptors).函数对象是描述符,因为它们定义了一个`__get__`方法,当使用点符号(如`Af`)访问对象时,该方法由魔法调用.描述符协议是(例如)_function_在实例上调用时如何转换为_bound方法_.通过`__dict__`,而不是使用点表示法,绕过描述符协议. (5认同)

Mar*_*ers 5

对于 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)