Search code examples
pythonglobal-variables

How to use globals()[] within a class


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

Solution

  • 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