1

If I want to call upon a variable like so:

boolean_0 = True
boolean_1 = False
no = 0
while no < 2:
    if globals()[f'boolean_{no}']:
        print(f'Boolean {no}', 'is True')
    else:
        print(f'Boolean {no}', 'is False')
    no += 1

how could I do it if it were in a class like this?

class boolean_func():
    def __init__(self):
        self.boolean_0 = True
        self.boolean_1 = False

    def check_status(self):
        no = 0
        while no < 2:
            if globals()[f'boolean_{no}']:
                print(f'Boolean {no}', 'is True')
            else:
                print(f'Boolean {no}', 'is False')
            no += 1
OshiniRB
  • 578
  • 1
  • 7
  • 21

2 Answers2

2

Try using self.__dict__ instead:

class boolean_func():
    def __init__(self):
        self.boolean_0 = True
        self.boolean_1 = False

    def check_status(self):
        no = 0
        while no < 2:
            if self.__dict__[f'boolean_{no}']:
                print(f'Boolean {no}', 'is True')
            else:
                print(f'Boolean {no}', 'is False')
            no += 1
x = boolean_func()
x.check_status()

Output:

Boolean 0 is True
Boolean 1 is False
U13-Forward
  • 69,221
  • 14
  • 89
  • 114
1

Use getattr. Its the normal way to get attributes from objects and has the advantage that it works with class variables too.

class boolean_func():
    
    def __init__(self):
        self.boolean_0 = True
        self.boolean_1 = False
   
    def check_status(self):
        no = 0
        while no < 2:
            if getattr(self, f'boolean_{no}'):
                print(f'Boolean {no}', 'is True')
            else:
                print(f'Boolean {no}', 'is False')
            no += 1

boolean_func().check_status()
tdelaney
  • 73,364
  • 6
  • 83
  • 116