sebastian20182018
sebastian20182018

Reputation: 83

Class variable not updating in depending other class variable

class Circle:
    a = 2
    b = a

#print class variables 
print(Circle.a)
print(Circle.b)

2
2

# updating class variable a to value 100
Circle.a = 100

# printing updated class variables
print(Circle.a)
print(Circle.b)

100
2

Why isn`t class variable b also updating to 100 ? Can I change the variable without a setter method ?

Upvotes: 0

Views: 883

Answers (2)

Mandera
Mandera

Reputation: 2992

This would be a good place for a @property decorator to make b point to a. Those however do not work on classmethods. I found https://stackoverflow.com/a/13624858/3936044 to create a nice little @classproperty decorator for us. Applying that to your code would look like this:

class classproperty:
    def __init__(self, fget):
        self.fget = fget

    def __get__(self, owner_self, owner_cls):
        return self.fget(owner_cls)

class Circle:
    a = 2

    @classproperty
    def b(cls):
        return cls.a

#print class variables
print(Circle.a)
print(Circle.b)

2
2

# updating class variable a to value 100
Circle.a = 100

# printing updated class variables
print(Circle.a)
print(Circle.b)

100
100

Upvotes: 1

timgeb
timgeb

Reputation: 78680

The names a and b both point to the same value (2) in memory (assignment never copies data). Then, a is reassigned to point to the value 100. Names are reassigned independently.

You did this:

a = 2
b = a

a ----> 2
        ^
       / 
b ----/

a = 100

a ----> 100
b ----> 2

Upvotes: 1

Related Questions