-1

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

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__方法中检索它?

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

4

1 回答 1

0

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

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

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

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

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

于 2020-04-11T15:00:50.297 回答