当使用__dict__分析属性时,my@staticmethod不是callable

Python 2.7.5 (default, Aug 29 2016, 10:12:21)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-4)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from __future__ import (absolute_import, division, print_function)
>>> class C(object):
...   @staticmethod
...   def foo():
...     for name, val in C.__dict__.items():
...       if name[:2] != '__':
...          print(name, callable(val), type(val))
...
>>> C.foo()
foo  False  <type 'staticmethod'>

这怎么可能?
如何检查静态方法是否可调用?
我在下面提供了一个更详细的示例:
脚本test.py
from __future__ import (absolute_import, division, print_function)

class C(object):

  @staticmethod
  def foo():
    return 42

  def bar(self):
    print('Is bar() callable?', callable(C.bar))
    print('Is foo() callable?', callable(C.foo))
    for attribute, value in C.__dict__.items():
      if attribute[:2] != '__':
        print(attribute, '\t', callable(value), '\t', type(value))

c = C()
c.bar()

Python2结果
> python2.7 test.py
Is bar() callable? True
Is foo() callable? True
bar      True    <type 'function'>
foo      False   <type 'staticmethod'>

对python3的结果相同
> python3.4 test.py
Is bar() callable? True
Is foo() callable? True
bar      True    <class 'function'>
foo      False   <class 'staticmethod'>

最佳答案

这种行为的原因是描述符协议。当C.foo中的staticmethod是a'foo'时,__dict__不会返回staticmethod而是一个正常函数(而staticmethod是一个描述符)。
简言之,在这种情况下,C.fooC.__dict__['foo']不同,而是C.__dict__['foo'].__get__(C)(另请参见Data model on descriptors文档中的部分):

>>> callable(C.__dict__['foo'].__get__(C))
True
>>> type(C.__dict__['foo'].__get__(C))
function

>>> callable(C.foo)
True
>>> type(C.foo)
function

>>> C.foo is C.__dict__['foo'].__get__(C)
True

在您的例子中,我将使用getattr检查可调用文件(它知道描述符以及如何访问它们),而不是使用类中存储为值的内容:
def bar(self):
    print('Is bar() callable?', callable(C.bar))
    print('Is foo() callable?', callable(C.foo))
    for attribute in C.__dict__.keys():
        if attribute[:2] != '__':
            value = getattr(C, attribute)
            print(attribute, '\t', callable(value), '\t', type(value))

打印内容(在python-3.x上):
Is bar() callable? True
Is foo() callable? True
bar      True    <class 'function'>
foo      True    <class 'function'>

python-2.x上的类型不同,但__dict__的结果相同:
Is bar() callable? True
Is foo() callable? True
bar      True    <type 'instancemethod'>
foo      True    <type 'function'>

07-24 18:28
查看更多