【问题标题】:How exactly are descriptor decorators called?描述符装饰器究竟是如何被调用的?
【发布时间】:2020-07-24 06:28:30
【问题描述】:

给定以下模拟静态方法的代码:

class StaticMethod(object):
    "Emulate PyStaticMethod_Type() in Objects/funcobject.c"
    def __init__(self, f):
        self.f = f
    def __get__(self, obj, objtype=None):
        print('getting')
        return self.f

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

    func2 = StaticMethod(func2)

当我打电话时: A.func2 我得到了我的期望:

getting
<function __main__.A.func2>

当我打电话时:A.func2() 我得到:

getting
hello

这是否意味着每当您调用 Descriptor Decorator 方法时,Python 首先会从 Descriptor 的 __get__ 方法中检索它?

如果是,那么该方法实际上是如何被调用的?引擎盖下到底发生了什么?

【问题讨论】:

  • 这里到底有什么让你吃惊的地方?

标签: python static-methods python-decorators python-descriptors


【解决方案1】:

这是否意味着每当您调用 Descriptor Decorator 方法时,Python 首先从 Descriptor 的 get 方法中检索它?

当您访问对象上的属性时,该对象的类具有作为描述符的类属性,该对象调用__get__ 并返回结果。

“描述符装饰器”并不是真正的东西,装饰器用于设置描述符的事实与其功能无关。

如果是,那么该方法实际上是如何被调用的?幕后究竟发生了什么?

如果您的意思是用staticmethod 修饰的底层函数,那么无论何时调用它都会调用该方法,描述符/staticmethod 本身并没有规定,它只是返回函数。

【讨论】:

    猜你喜欢
    • 2019-08-01
    • 2017-07-10
    • 1970-01-01
    • 2013-03-12
    • 2015-07-05
    • 2012-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多