【问题标题】:Static method syntax confusion静态方法语法混乱
【发布时间】:2015-12-12 03:56:39
【问题描述】:

这就是我们在 Python 中制作静态函数的方式:

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

A.fun()

这按预期工作并打印hello

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

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

A().fun()

它也可以按预期工作并打印hello

我对以下情况感到困惑:

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

在上述情况下,没有staticmethod,也没有self。 Python 解释器可以接受这个定义。但是,我们不能将其称为上述任何一种方法,即:

A.fun()
A().fun()

两者都给出错误。

我的问题是:有什么方法可以调用这个函数吗?如果不是,为什么 Python 一开始就不给我语法错误?

【问题讨论】:

    标签: python python-2.7 methods static-methods


    【解决方案1】:

    Python 不会给您一个语法错误,因为方法的绑定(负责传递self)是一个运行时操作。

    仅当您在类或实例上查找方法时,才会绑定方法(因为函数是descriptors,它们在以这种方式查找时会生成方法)。这是通过descriptor.__get__() method 完成的,它由object.__getattribute__() method 调用,当您尝试访问A 类或A() 实例上的fun 属性时,Python 会调用它。

    您始终可以“解包”绑定的方法,并使用下面的解包函数直接调用它:

    A.fun.__func__()
    

    顺便说一句,这正是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!
    

    【讨论】:

      猜你喜欢
      • 2013-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-11
      • 2020-04-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多