how a function in python is getting called by just typing the name of function and not using brackets
首先,为了找到两个数的"lcm",我做了一个函数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | 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) |
输出:
1 2 | hcf is 2 lcm is 4 |
号
我觉得你不懂装饰。让我们做一个最小的例子。
1 2 3 4 5 6 7 8 9 10 11 12 | 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" |
我们有一个简单的函数
注意
1 2 3 | @my_decorator def my_function(a, b): return a + b |
号
等于
1 2 3 4 | def my_function(a, b): return a + b my_function = my_decorator(my_function) |
因为
行动中:
1 2 | >>> my_function(1, 2) my_function produced 3 |
。
注意,在示例中的每一点上,当调用函数时,都会出现括号语法。以下是我发布的第一个代码块中发生的所有函数调用,顺序如下:
如果您想了解
正如您注意到的,
1 2 3 | @decor def lcm(a, b): // ... |
等于
1 2 3 4 | def lcm(a, b): // ... lcm = decor(lcm) |
。
执行后,