RealBeginner
RealBeginner

Reputation: 73

How to trigger function inside class more effectively?

I am building a model with Python by using class method and there are serval functions inside the class.

The structure of my model is something like that:

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')

Function b needs to be triggered after function a has triggered.So, I write another function to solve this problem, where r1,r2 r3 are the name of each object under class.The structure of that function is like that:

def A_then_B ():
    r1.function_a()
    r2.function_a()
    r3.function_a()
    r1.function_b()
    r2.function_b()
    r3.function_b()

It looks fine with only 3 objects, however, there are 24 objects under class method. And the function itself will become super long and not effective enough. So, how can I modify my function so that it will not too long while doing the same work (all the objects trigger function a then trigger function b) ?

Upvotes: 4

Views: 150

Answers (1)

quamrana
quamrana

Reputation: 39354

Put your objects in a collection and iterate through them:

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()

Better yet, pass the objects into your functions:

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)

Upvotes: 5

Related Questions