社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Python

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

Pardeep Singh Brar • 4 年前 • 801 次点击  

首先要找到两个数字的“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
 
801 次点击  
文章 [ 2 ]  |  最新文章 4 年前