使用列表理解的函数列表 [英] call list of function using list comprehension
本文介绍了使用列表理解的函数列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我可以调用函数列表并使用列表理解吗?
def func1():return 1
def func2():return 2
def func3 :return 3
$ b fl = [func1,func2,func3]
fl [0]()
fl [1]()
fl [ 2]()
我知道我可以做
for f in:
f()
<
[f()for f in fl]
$ c $如果我的函数列表在类中,例如
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()
它是否有效?
解决方案 <当然你可以像FábioDiniz说的那样:),
然而,对于用作可调用对象的类方法,必须给出一个对象作为参数:
fobj = F()
for f in fobj.fl:
f(fobj)
必须将该对象作为可调用参数给出,因为当您查看方法 def funcX(self)的定义时:
该方法需要一个参数 self
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?
解决方案 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:
fobj= F()
for f in fobj.fl:
f(fobj)
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 argument "self"
这篇关于使用列表理解的函数列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文