-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

2
  • 1
    Have you tried it? Why are you adding strings to your list of objects instead of objects themselves? Commented May 18, 2023 at 7:15
  • 2
    List should be [obj1,obj2]. Commented May 18, 2023 at 7:16

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.