Search code examples
pythonclassstatic-variablesclass-variables

Changing static class variables


How is it possible to change static variables of a class? I want it to be changed by some sort of input.

class MyClass: 
    
    var1 = 1
    var2 = 4

    def __init__(self, var3, var4):
        self.var3 = var3
        self.var4 = var4

It is var1 og var2 that i want to be changable, or want to know how to change.


Solution

  • class Whatever():
        b = 5
        def __init__(self):
            Whatever.b = 9999
    
    boo = Whatever()
    print(boo.b) # prints 9999
    
    boo.b = 500
    print(boo.b) # prints 500
    
    Whatever.b = 400
    print(boo.b) # prints 500
    
    # since its a static var you can always access it through class name
    # Whatever.b