[英]decorators in python
I am trying to understand the functioning of decorators. 我试图了解装饰器的功能。 What am i doing wrong in the following code.
我在下面的代码中做错了什么。 Please do correct it
请更正
As I have understood when aFunction() is called it in turn calls myDecorator() which also makes a call to afunction(). 据我了解,当调用aFunction()时,它依次调用myDecorator(),后者也对afunction()进行了调用。 Right?
对?
Also how to pass parameters into afunction() 还有如何将参数传递给afunction()
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
f(1) # Prove that function definition has completed
def __call__(self):
print "inside myDecorator.__call__()"
@myDecorator
def aFunction(*a):
print a
print "inside aFunction()"
print "Finished decorating aFunction()"
aFunction(2)
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
# save a reference to the real function, so it can be called later
self.f = f
def __call__(self, *args, **kwargs):
print "inside myDecorator.__call__()"
# call the real function and return its result
# passing it any and all arguments
return self.f(*args, **kwargs)
@myDecorator
def aFunction(*a):
print a
print "inside aFunction()"
print "Finished decorating aFunction()"
aFunction(1)
print "Finished calling aFunction()
Your __call__
method is missing the parameter, which you give to aFunction
. 您的
__call__
方法缺少提供给aFunction
的参数。
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
f(1) # Prove that function definition has completed
self.__function = f
def __call__(self, *args):
# the *args magic is here to mirror the original parameter list of
# the decorated function. But it is better to place here parameter list
# of the function you want to decorate, in order to minimize error possibilities
print "inside myDecorator.__call__()"
return self.__function(*args)
@myDecorator
def aFunction(*a):
print a
print "inside aFunction()"
print "Finished decorating aFunction()"
aFunction(1)
aFunction('a', 23, 42)
f
, in __init__
, needs to be saved, then the __call__
method needs to call it. 需要保存
__init__
f
,然后需要__call__
方法调用它。 Something like this: 像这样:
class myDecorator(object):
def __init__(self, f):
print "inside myDecorator.__init__()"
self.f = f
print "function has been saved"
def __call__(self, *args):
print "inside myDecorator.__call__()"
result = self.f(args)
print "done with f()"
return result
@myDecorator
def aFunction(*a):
print a
print "inside aFunction()"
aFunction(1)
What happens with decoration is that the original function is replaced with whatever the decorator returns. 装饰发生的事情是原始函数被装饰器返回的内容所取代 。 Your original code, however, was not saving any reference to
aFunction
so it was getting lost. 但是,您的原始代码没有保存对
aFunction
任何引用,因此丢失了它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.