How to iterate through objects in a class?

Question:

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.

Asked By: Twitch008

||

Answers:

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

Answered By: x pie

I think this will answer your question.

class foo:
    def __init__(self):
        self.a = 'string1'
        self.b = f'{self.a}string2'

bar = foo()

for i in dir(bar):
    print("obj.%s = %r" % (i, getattr(bar, i)))

# obj.__class__ = <class '__main__.foo'>
# obj.__delattr__ = <method-wrapper '__delattr__' of foo object at 0x000001C28C2A3B80>
# obj.__dict__ = {'a': 'string1', 'b': 'string1string2'}
# obj.__dir__ = <built-in method __dir__ of foo object at 0x000001C28C2A3B80>
# [...]
# obj.a = 'string1'
# obj.b = 'string1string2'
Answered By: JAdel
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.