0

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.

halfer
  • 19,824
  • 17
  • 99
  • 186
Twitch008
  • 29
  • 4
  • Do the answers to this [question](https://stackoverflow.com/questions/19151/how-to-build-a-basic-iterator) help at all? – quamrana Jul 14 '22 at 17:22

2 Answers2

2

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

x pie
  • 552
  • 1
  • 10
1

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'
JAdel
  • 1,309
  • 1
  • 7
  • 24