简体   繁体   English

Python 内部 function 运行时复杂度

[英]Python inner function runtime complexity

Suppose I wrote a function to create another function, say like:假设我写了一个 function 来创建另一个 function,比如:

def g(x):
    #do stuff
    def h(y):
        return x*y
    return h

my_func = g(10)
for i in range(100):
    print(my_func(i))

In my for loop I am calling my_func a hundred times, however since I only call g once to create my_func I would expect that the #do stuff bit of my code will only run once at the beginning and not once every iteration of the loop.在我for循环中,我调用了my_func一百次,但是由于我只调用一次g来创建my_func ,我希望我的代码的#do stuff位只会在开始时运行一次,而不是每次循环迭代运行一次。

Can anyone confirm that this is actually the case or will it run every single time inside the for loop?任何人都可以确认这确实是这种情况,还是会在 for 循环中每次都运行? I couldn't find a satisfactory answer elsewhere.我在其他地方找不到满意的答案。

Correct, if there was a line of code where #do stuff is, it would only run once in this example.正确,如果有一行代码在#do stuff所在的位置,则在此示例中它只会运行一次。

Tip: if you had replaced it with print("test") you could have checked this for yourself.提示:如果你用print("test")替换了它,你可以自己检查一下。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM