Python 如何更有效地触发类内函数?

Python 如何更有效地触发类内函数?,python,function,Python,Function,我正在使用类方法用Python构建一个模型,类中有几个函数 我的模型的结构是这样的: class testing (): def __init__ (self, number, lane, position): self.number = number self.lane = lane self.position = position def function_a (self): print('function_a'

我正在使用类方法用Python构建一个模型,类中有几个函数

我的模型的结构是这样的:

class testing ():
    def __init__ (self, number, lane, position):
        self.number = number
        self.lane = lane
        self.position = position
    def function_a (self):
        print('function_a')
    def function_b(self):
        print('function_b')
    def function_c(self):
        print('function_c')
    def function_d(self):
        print('function_d')
def A_then_B ():
    r1.function_a()
    r2.function_a()
    r3.function_a()
    r1.function_b()
    r2.function_b()
    r3.function_b()
函数b需要在函数a触发后触发。因此,我编写了另一个函数来解决这个问题,其中r1,r2 r3是类下每个对象的名称。该函数的结构如下:

class testing ():
    def __init__ (self, number, lane, position):
        self.number = number
        self.lane = lane
        self.position = position
    def function_a (self):
        print('function_a')
    def function_b(self):
        print('function_b')
    def function_c(self):
        print('function_c')
    def function_d(self):
        print('function_d')
def A_then_B ():
    r1.function_a()
    r2.function_a()
    r3.function_a()
    r1.function_b()
    r2.function_b()
    r3.function_b()

只有3个对象看起来很好,但是,类方法下有24个对象。而功能本身将变得超长且不够有效。那么,如何修改我的函数,使其在执行相同的工作时不会太长时间(所有对象触发函数a,然后触发函数b)

将对象放入一个集合中并对其进行迭代:

def A_then_B ():
   objects = (r1, r2)   # add as many as you have here
   for r in objects:
       r.function_a()
   for r in objects:
       r.function_b()
更好的方法是将对象传递到函数中:

def A_then_B(objects):
   for r in objects:
       r.function_a()
   for r in objects:
       r.function_b()

def C_then_D(objects):
   for r in objects:
       r.function_c()
   for r in objects:
       r.function_d()

objects = (r1, r2)   # add as many as you have here
A_then_B(objects)
C_then_D(objects)

你不能把对象放在一个列表中,然后使用一个循环吗?