python pyqt:如何使用for循环调用多个模块?

时间:2012-10-17 17:18:58

标签: python pyqt4

我想在paintEvent()中使用for循环调用多个模块,比如

 def fun1(self,paint,a,b):
     do something ...
 def fun2(self,paint,a,b):
     do something ...
 def fun3(self,paint,a,b):
     do something .... 

 def paintEvent(self,event=None):
     for i in range (1,3):
        self.fun[i](self,paint,a,b)

基本上我的fun1,fun2和fun3正在绘制一些小部件并且几乎相同。请帮我看看如何使用for循环调用这些函数。

2 个答案:

答案 0 :(得分:3)

您可以执行以下操作:

def fun1(self,paint,a,b):
    do something ...
def fun2(self,paint,a,b):
    do something ...
def fun3(self,paint,a,b):
    do something .... 

self.fun = [self.fun1,self.fun2,self.fun3]

def paintEvent(self,event=None):
    for i in range (1,3):
       self.fun[i](self,paint,a,b)

如果fun1,fun2和fun3几乎与你所说的相同,你应该考虑将它们组合成一个你可以使用附加参数调用的函数。

答案 1 :(得分:2)

你可以做点什么:

def fun1(self, paint, a, b):
    pass

def fun2(self, paint, a, b):
    pass

def fun3(self,paint, a, b):
    do something .... 


def paintEvent(self, event=None):
    functions = [self.fun1, self.fun2, self.fun3]
    for func in functions:
        func(paint, a, b)

或者如果你确定函数名称,就像它们有类似的命名模式一样,即使这样也可行:

def paintEvent(self, event=None):
    for attr_name in dir(self):
        if attr_name.startswith('fun'):
            func = getattr(self, attr_name)
            func(paint, a, b)