-3

I have class:

class Services:
    
    def __init__(self,a1,b1):
        self.a1 = a1
        self.b1 = b1
        
        
    def do_something(self):
        print('hello')
        
        

obj1 = Services('aaa','bbb')
obj2 = Services('aaa1','bbb1')

objlist =['obj1','obj2']

for i in objlist:
    i.do_something()

Is is possible to loop objects and call class methods for multiple objects? Thanks

miojamo
  • 723
  • 2
  • 14
  • 31

1 Answers1

2

You can loop through a list of objects and call their methods. However, in your list, you need to store the objects and not strings. Modified code:

#Create your class
class Services:
    
    def __init__(self,a1,b1):
        self.a1 = a1
        self.b1 = b1      
        
    def do_something(self):
        print('hello')
        
#Create two objects
obj1 = Services('aaa','bbb')
obj2 = Services('aaa1','bbb1')

#Create a list of objects
objlist = [obj1,obj2]

#Loop through the list of objects and call their method
for obj in objlist:
    obj.do_something()

Output:

hello
hello
Dinux
  • 644
  • 1
  • 6
  • 19