Py学习  »  Python

python中的函数是如何通过只键入函数名而不使用括号来调用的

Pardeep Singh Brar • 5 年前 • 1559 次点击  

首先要找到两个数字的“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)

输出:

hcf is 2
lcm is 4
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/39740
 
1559 次点击  
文章 [ 2 ]  |  最新文章 5 年前