ALI HAIDAR
ALI HAIDAR

Reputation: 88

Calling functions of a class from a list of functions

Let example be a class of five functions including the constructor:

class example():
    def __init__(self):
         self.best_A=None
         self.best_B=None
         self.best_C=None

    def run_A(self):
        #code here
        self.best_A= ..
        pass

    def run_B(self):
        #code here
        self.best_B= ..
        pass
    
    def run_B(self):
        #code here
        self.best_C= ..
        pass

    def run(self):
       self.run_A()
       self.run_B()
       self.run_C()

Rather than typing all the functions in the function run(), how to create a list of function names and call them by iterating through the list ?

Upvotes: 0

Views: 32

Answers (1)

Something like that could help:

class example():
   def __init__(self):
        self.best_A=None
        self.best_B=None
        self.best_C=None
        self.list_of_fun = [self.run_A, self.run_B, self.run_C, self.run_C] 

   def run_A(self):
       #code here
       self.best_A= ..
       pass

   def run_B(self):
       #code here
       self.best_B= ..
       pass
   
   def run_B(self):
       #code here
       self.best_C= ..
       pass

   def run(self):
       for fun in self.list_of_fun:
           # code the way the functions are intent to be used

Upvotes: 1

Related Questions