0

我想在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 循环调用这些函数。

4

2 回答 2

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 与您所说的几乎相同,您应该考虑将它们组合成一个可以使用附加参数调用的函数。

于 2012-10-17T17:32:15.223 回答
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)
于 2012-10-17T17:32:56.363 回答