【问题标题】:How is a staticmethod not bound to to the "staticmethod" class?静态方法如何不绑定到“静态方法”类?
【发布时间】:2020-02-27 18:10:37
【问题描述】:

我试图了解描述符在 python 中是如何工作的。我得到了大局,但我在理解 @staticmethod 装饰器时遇到了问题。

我特指的代码来自对应的python doc:https://docs.python.org/3/howto/descriptor.html

class Function(object):
    . . .
    def __get__(self, obj, objtype=None):
        "Simulate func_descr_get() in Objects/funcobject.c"
        if obj is None:
            return self
        return types.MethodType(self, obj)
class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"

    def __init__(self, f):
        self.f = f

    def __get__(self, obj, objtype=None):
        return self.f

我的问题是:当在最后一行访问self.f 时,f 本身不会被识别为描述符(因为每个函数都是非数据描述符)并因此绑定到 self,即一个静态方法对象?

【问题讨论】:

    标签: python python-decorators python-descriptors


    【解决方案1】:

    描述符是类属性,因此需要在类级别定义。

    上一个示例中的函数f 是一个实例属性,通过将名为f 的属性绑定到f 引用的输入对象,在__init__ 中设置。由于它不是类属性,因此永远不会被归类为描述符。


    现在,从调用者的角度来看,staticmethod 是一个类属性,因为它是在类级别实现的,例如喜欢:

    class Foo:
        @staticmethod
        def bar():
            return 10
    

    装饰器只是一个语法糖,你可以很好地写成:

    class Foo:
        def bar():
            return 10
        bar = staticmethod(bar)
    

    所以在这种情况下它将被视为描述符。

    【讨论】:

      猜你喜欢
      • 2011-01-17
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      • 2021-11-29
      • 2011-08-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多