Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

(Please forgive any typos. Typing this up quickly on my phone)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading