Why class atribute doesn't change on update

Viewed 23

I am wondering why the class attribute doesn't change in the code below. As you can see the value remains the same, despite being changed in class A?

class A:
    valueA = 1.05
        
class User:
    
    def __init__(self,name):
        
        self.name = name
        self.value = A.valueA
        


user = User('Alice')
print(user.value)
A.valueA = 1.1
print(A.valueA)
print(user.value)

output:

1.05
1.1
1.05
1 Answers

I don't understand why it should? ValueA is an number which is an immutable object(everything is a object), so valueA is just some sort of referencethat points to value 1.05.

To make more clear, here is an example of how does it behave:

class A(object):
    val = [1,2,3]

class B(object):

    def __init__(self):
        self.myval = A.val


print(A.val)
# prints [1,2,3]
obj = B()
print(obj.myval)
# prints [1,2,3] because its starts to point to the same list
A.val[0] = 5
print(obj.myval)
# prints [5,2,3] because both still points to the same list, 
# and you just changed it fist value
A.val = [4,5,6,7]
print(A.val)
# prints new list [4,5,6,7]
print(obj.myval)
# prints [5,2,3] because it still points to old list.
obj2 = B()
print(obj2.myval)
# prints new list [4,5,6,7] because assignment was done after A.val changed

also here is a good article about variables in python https://realpython.com/python-variables/#object-references

Related