在循环中定义函数会为每次迭代重新定义函数,或者python可以对此进行优化?
有时我为了方便而定义临时函数在循环中定义函数会为每次迭代重新定义函数,或者python可以对此进行优化?,python,Python,有时我为了方便而定义临时函数 def parse_time(string): h, m = string.split(':') return timedelta(hours=h, minutes=m) something = parse_time(re.search(r'(\d\d:\d\d)', line).group(1)) 没关系,现在我将上面的代码片段放在一个循环中: for line in file: # ... some code def parse_
def parse_time(string):
h, m = string.split(':')
return timedelta(hours=h, minutes=m)
something = parse_time(re.search(r'(\d\d:\d\d)', line).group(1))
没关系,现在我将上面的代码片段放在一个循环中:
for line in file:
# ... some code
def parse_time(string):
h, m = string.split(':')
return timedelta(hours=h, minutes=m)
something = parse_time(re.search(r'(\d\d:\d\d)', line).group(1))
我的问题是,python会对此进行优化还是会为每次迭代重新定义函数?我怎样才能证实这一点
在这方面,在循环中定义函数是浪费的。由于
def
关键字,每次都会(重新)定义函数。一个简单的测试:
>>> def foo(x):
... print(x + 1)
...
>>> id(foo)
1971729284632
>>> def foo(x):
... print(x + 1)
...
>>> id(foo)
1971739226320
每次迭代它都(重新)定义它,但为什么你首先要这样做?你不必在for循环中定义函数就可以在那里使用它。我并不需要这个,但有时我需要一个我不想写为lambdas的小函数,将这个微小的函数移到范围外似乎是不可取的。有时,我们在闭包中对变量进行编码,以模拟函数调用的状态,最后,就像在使用它的地方定义的代码一样