class级装饰器什么时候装饰?

When does class level decorator decorates?

我创建了一个装饰器来装饰 class 的所有实例方法。为此,我编写了以下代码。

def debug(func):
    msg = func.__name__

    @wraps(func)
    def wrapper(*args, **kwargs):
        print(msg)
        return func(*args, **kwargs)
    return wrapper 

# Decorator for all the methods in a class
def debugmethods(cls):
    for key, val in vars(cls).items():
        if callable(val):
            setattr(cls, key, debug(val))
    return cls

@debugmethods
class Spam:
    def foo(self):
        pass

    def bar(self):
        pass

现在我想了解它是如何工作的,我的意思是这种装饰什么时候会发生,我该如何检查?

a) 已经发生了?

b) 当我第一次访问垃圾邮件时 class?例如

for key, val in Spam.__dict__.items():
        print(key, val)

c) 当我第一次实例化 Spam class 时?例如

 spam = Spam()
 for key, val in Spam.__dict__.items():
     print(key, val)

如果添加几行打印,实际上很容易看到:

print('Deocrator is being defined')
def deco(cls):
    print('Decorator is called')
    cls.decorated = True
    return cls

print('Foo is being defined')
@deco
class Foo:
    print('Foo class attributes are being set')
    def __init__(self):
        print('Foo is being instantiated')

print('Foo class is being referenced in main script')
print(f'Foo is decorated: {Foo.decorated}')
print('Foo instance is being created in main script')
print(Foo())

结果:

Deocrator is being defined
Foo is being defined
Foo class attributes are being set
Decorator is called    # <--- decoration happens immediately after definition of Foo
Foo class is being referenced in main script
Foo is decorated: True
Foo instance is being created in main script
Foo is being instantiated
<__main__.Foo object at 0x00789150>

简而言之,答案很像@jonrsharpe 所说的,它已经发生了。想想视觉效果会有所帮助。