2

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.

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343

4 Answers4

4
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
JoDavid
  • 393
  • 2
  • 8
  • 2
    this is wrong. The last `print(boo.b)` prints 500, not 400. – PoweredByRice Jul 10 '20 at 16:41
  • You are right @PoweredByRice. The reason why, in my understanding, is that the line `boo.b = 500` is creating an object variable, `boo.b`, which is shadowing the class variable `whatever.b`. So, when in the last line you print `boo.b`, you are printing the "new" object variable. This can be checked by creating the whatever class from scratch, and then running `boo = whatever()`, `whatever.b = 400` and `print(boo.b)`. the result now would be 400. – jgbarah Jan 13 '21 at 18:09
0

If you want to change the class variables, you can assign them to the variables in the __init__ scope:

class MyClass: 
  var1 = 1
  var2 = 4
  def __init__(self, var3, var4):
    self.var1 = var3
    self.var2 = var4

c = MyClass(100, 200)
>>>c.var1, c.var2

Output:

(100, 200)
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
0

It depends when you need to rebind the class attributes. You can also do so later when the object is created:

mc = MyClass(1, 2)
mc.var1 = 20
mc.var2 = 40

There is no difference between an attribute created or changed within the class body to one created outside by assigning to an attribute.

haircode
  • 301
  • 1
  • 4
  • 13
0

You can change the class variables by class name as shown below:

class MyClass: 
    var1 = 1
    var2 = 2
        
MyClass.var1 = 10 # By class name
MyClass.var2 = 20 # By class name

print(MyClass.var1) # Class variable
print(MyClass.var2) # Class variable

Output:

10
20

Be careful, if you try to change the class variables by object, you are actually adding new instance variables but not changing the class variables as shown below:

class MyClass: 
    var1 = 1 
    var2 = 2 
        
obj = MyClass()
obj.var1 = 10 # Adding a new instance variable but not changing the class variable
obj.var2 = 20 # Adding a new instance variable but not changing the class variable

print(MyClass.var1) # Class variable
print(MyClass.var2) # Class variable
print(obj.var1) # New instance variable
print(obj.var2) # New instance variable

Output:

1
2
10
20
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129