Par*_*rar 1 python python-3.x python-decorators
首先要找到两个数字的"lcm"我做了一个函数lcm(a, b).然后我想找到"hcf",所以我做了一个装饰器decor并hcf(a, b)在其中定义了一个函数.然后我通过输入函数的名称返回此函数,我没有使用括号,但它仍然有效.我不明白为什么这个功能工作,即使我没有使用括号.
def decor(lcm_arg): # just to practice decorators
def hcf(a, b):
if a > b:
a, b = b, a
while True:
if b % a == 0:
print("hcf is", a)
break
else:
a, b = b % a, a
return lcm_arg(a, b)
return hcf # how hcf function is working without using brackets
@decor
def lcm(a, b):
if a > b:
a, b = b, a
for x in range(b, a*b+1, b):
if x % a == 0:
print("lcm is", x)
break
lcm(2, 4)
Run Code Online (Sandbox Code Playgroud)
输出:
hcf is 2
lcm is 4
Run Code Online (Sandbox Code Playgroud)
我不认为你理解装饰者.让我们举一个最小的例子.
def my_decorator(some_function):
def new_function(*args, **kwargs):
'announces the result of some_function, returns None'
result = some_function(*args, **kwargs)
print('{} produced {}'.format(some_function.__name__, result))
return new_function # NO FUNCTION CALL HERE!
@my_decorator
def my_function(a, b):
return a + b
my_function(1, 2) # will print "my_function produced 3"
Run Code Online (Sandbox Code Playgroud)
我们有一个简单的函数my_function,它返回它的两个参数和一个装饰器的总和,它只打印出它装饰的任何函数的结果.
注意
@my_decorator
def my_function(a, b):
return a + b
Run Code Online (Sandbox Code Playgroud)
相当于
def my_function(a, b):
return a + b
my_function = my_decorator(my_function)
Run Code Online (Sandbox Code Playgroud)
因为my_decorator接受一个函数作为参数(这里我们给它my_function)并返回一个新函数 new_function(不调用它!),我们有效地覆盖,my_function因为我们将名称重新分配给任何my_decorator返回.
在行动:
>>> my_function(1, 2)
my_function produced 3
Run Code Online (Sandbox Code Playgroud)
请注意,在调用函数时示例中的每个点,都会出现括号语法.以下是我发布的第一个代码块中发生的所有函数调用,依次为:
my_decorator(my_function)被调用,返回值被重新赋值给名称my_function.这可以通过@语法或更明确地在等效代码段中进行.my_function(1, 2)叫做.此时,my_function是new_function装饰者返回的那个.脑子把它解析为new_function(1, 2).new_function我们给出的参数中,我们给出的参数my_decorator叫做(result = some_function(*args, **kwargs)),它恰好是my_function 在步骤1中发生的重新分配之前的值.print 叫做.如果你想了解如何new_function坚持,some_function尽管my_decorator已经从它的调用返回,我建议调查主题自由变量和闭包.