使用列表理解调用函数列表
我可以调用函数列表并使用列表理解吗?
def func1():
return 1
def func2():
return 2
def func3():
return 3
fl = [func1, func2, func3]
fl[0]()
fl[1]()
fl[2]()
我知道我可以做
for f in fl:
f()
,但我可以做下面吗?
[f() for f in fl]
对于那些好心人来说,还有一个问题,例如,如果我的函数列表在课堂上,
class F:
def __init__(self):
self.a, self.b, self.c = 0, 0, 0
def func1(self):
self.a += 1
def func2(self):
self.b += 1
def func3(self):
self.c += 1
fl = [func1, func2, func3]
fobj = F()
for f in fobj.fl:
f()
它是否有效?
can I call a list of functions and use list comprehension?
def func1():
return 1
def func2():
return 2
def func3():
return 3
fl = [func1, func2, func3]
fl[0]()
fl[1]()
fl[2]()
I know I can do
for f in fl:
f()
but can I do below ?
[f() for f in fl]
A additional question for those kind people, if my list of functions is in class, for example
class F:
def __init__(self):
self.a, self.b, self.c = 0, 0, 0
def func1(self):
self.a += 1
def func2(self):
self.b += 1
def func3(self):
self.c += 1
fl = [func1, func2, func3]
fobj = F()
for f in fobj.fl:
f()
does it work?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
绝对地 :)
Absolutely :)
当然可以,正如 Fábio Diniz 所说:)
但是,对于用作可调用对象的类方法,必须将对象作为参数给出:
该对象必须作为可调用对象的参数给出,因为当您查看方法
def funcX(self):
该方法需要一个参数self
Of course you can as Fábio Diniz said :)
However for the class method when used as a callable, an object must be given as an argument:
The object must be given as an argument to the callable because when you look at the definition of the method
def funcX(self):
the method needs one argumentself
是的,你可以。结果列表将保存函数的返回值。
Yes, you can. The resultant list will hold the return values of your functions.
是的,您可以 - 函数会按预期调用。
Yes, you can - the functions get called as intended.