我创建了一个装饰器来装饰一个类的所有实例方法。我已经编写了以下代码。
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)第一次访问垃圾邮件类?例如。
for key, val in Spam.__dict__.items():
print(key, val)
c)第一次实例化Spam类时?例如。
spam = Spam()
for key, val in Spam.__dict__.items():
print(key, val)
答案 0 :(得分:2)
如果添加一些打印行,实际上很容易看到它:
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所说的那样,已经发生了。只要看清楚视觉效果就可以。