静态方法语法混乱

Sai*_*ait 2 python methods static-methods python-2.7

这就是我们在Python中创建静态函数的方法:

class A:
   @staticmethod
   def fun():
      print 'hello'

A.fun()
Run Code Online (Sandbox Code Playgroud)

这按预期工作并打印hello.

如果它是成员函数而不是静态函数,我们使用self:

class A:
   def fun(self):
      print 'hello'

A().fun()
Run Code Online (Sandbox Code Playgroud)

这也按预期工作并打印hello.

我的困惑是以下情况:

class A:
   def fun():
      print 'hello'
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,没有staticmethod,也没有self.Python解释器可以使用这个定义.但是,我们不能称之为上述任何一种方法,即:

A.fun()
A().fun()
Run Code Online (Sandbox Code Playgroud)

两者都有错误.

我的问题是:有什么办法可以调用这个函数吗?如果没有,为什么Python首先不会给我一个语法错误?

Mar*_*ers 8

Python没有给你一个语法错误,因为方法的绑定(负责传入self)是一个运行时操作.

只有当你在类或实例上查找方法时,才会绑定一个方法(因为函数是描述符,它们在以这种方式查找时会生成一个方法).这是通过descriptor.__get__()方法调用的object.__getattribute__()方法完成的,当您尝试访问类或实例fun上的属性时,Python会调用该方法.AA()

您可以随时"解包"绑定方法并触及下面的未包装函数直接调用它:

A.fun.__func__()
Run Code Online (Sandbox Code Playgroud)

顺便说一下,这正是做什么的staticmethod; 它是"拦截"描述符绑定并返回原始函数对象而不是绑定方法.换句话说,staticmethod 撤消正常的运行时方法绑定:

演示:

>>> class A(object): pass
... 
>>> def fun(): print 'hello!'
... 
>>> fun.__get__(None, A)  # binding to a class
<unbound method A.fun>
>>> fun.__get__(None, A)()   # calling a bound function, fails as there is no first argument
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method fun() must be called with A instance as first argument (got nothing instead)
>>> fun.__get__(None, A).__func__  # access the wrapped function
<function fun at 0x100ba8378>
>>> staticmethod(fun).__get__(None, A)  # staticmethod object just returns the function
<function fun at 0x100ba8378>
>>> staticmethod(fun).__get__(None, A)()  # so calling it works
hello!
Run Code Online (Sandbox Code Playgroud)