Search code examples
pythonclassobjectiterable

How to iterate through objects in a class?


For a script I'm writing I would like to be able to something like this.

class foo:
    __init__(self):
        self.a = 'path1'
        self.b = f'{self.a}path2'

bar = foo()

for i in bar:
    if not os.path.isdir(i):
        os.mkdir(i)

But I can't quite figure out how to make the class iterate through the objects.


Solution

  • Is this what you need?

    class foo:
        def __init__(self):
            self.a = 'string1'
            self.b = f'{self.a}string2'
    
    bar = foo()
    
    for attr, value in bar.__dict__.items():
            print(attr, value)
    

    enter image description here