作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如何编写以下代码以使并非所有功能都相同?
>>> def g(x):
... l = []
... for i in range(1,10):
... def f(x):
... return x + i
... l.append(f)
... return l
这个想法应该是g
返回 9 个函数的列表,其中第一个函数返回 x+1
第二个x+2
然而,由于在 python 中一切都是对象,所有先前的函数定义都将被覆盖。我该如何解决这个问题?
最佳答案
这不会覆盖最终列表中的函数
def make_f(x, i):
def f():
return x + i
return f
def g(x):
l = []
for i in range(1, 10):
l.append(make_f(x, i))
return l
for f in g(10):
print f()
11
12
13
14
15
16
17
18
19
关于python - 如何在Python中返回函数的多种变体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44825698/
我是一名优秀的程序员,十分优秀!