Search code examples
pythonglobal-variablesstatic-variables

Changing a variable used in a class?


I'm using a variable as part of a string within a class, however printing the string shows what the variable had been set to at the start of the program, rather than what it's been changed to

My current code basically says this:

b = 0
class addition:
    a = 1 + b

def enter():
    global b;
    b = input("Enter a number: ")
    print(addition.a) - Prints "1" regardless of what is typed in
enter()

How would I "rerun" the class to use the value assigned to the variable in the function?


Solution

  • The easiest way to use the reassigned value of b is creating classmethod a:

    b = 0
    class addition:
        @classmethod
        def a(cls):
            return 1 + b
    
    def enter():
        global b;
        b = int(input("Enter a number: ")) # convert string input to int
        print(addition.a()) # calling a with ()
    enter()
    

    But it breaks your original semantics to call addition.a without (). If you really need to save it, there is a way using metaclass:

    class Meta(type):
        def __getattr__(self, name):
            if name == 'a':
                return 1 + b
            return object.__getattr__(self, name)
    
    b = 0
    class addition(metaclass=Meta):
        pass
    
    def enter():
        global b;
        b = int(input("Enter a number: "))
        print(addition.a) # calling a without ()
    enter()