Python装饰器在类中调用

2024-09-28 17:29:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图理解Python decorators,并试图编写与此类似的程序:

class myDecorator(object):
   def __init__(self, f):
      print ("inside myDecorator.__init__()")
      f() # Prove that function definition has completed

   def __call__(self):
      print ("inside myDecorator.__call__()")

@myDecorator
def aFunction():
   print ("inside aFunction()")

print ("Finished decorating aFunction()")

aFunction()

问题是我不理解类的__call__方法是如何通过最后调用aFunction()来调用的。

是由aFunction()替换为myDecorator.__call__(aFunction)。 你能帮帮我吗?没有decorators的等价程序是什么?

谢谢!


Tags: self程序decoratorsthatobjectinitdeffunction