1

from my past knowledge of python oop i know that python has a single copy of a class variable for all class instances;it means:

>>> class A: foo = []
>>> a, b = A(), A()
>>> a.foo.append(5)
>>> b.foo
[5]

but when i do this:

>>> class A():
    cl_var=5
    def __init__(self,b):
        self.obj_var=b


>>> a1,a2=A(2),A(5)
>>> a1.cl_var
5
>>> a1.cl_var=23
>>> a2.cl_var
5 

why a2.cl_var not changing to 23 ?

1 Answer 1

4

When you assign to a1.cl_var you rebind cl_var associated with a1. This does not affect a2.cl_var.

>>> id(a1.cl_var), id(a2.cl_var)
(11395416, 11395416)

As you can see, a1.cl_var and a2.cl_var are the same object.

However, when you assign to a1.cl_var, they become different objects:

>>> a1.cl_var=23
>>> id(a1.cl_var), id(a2.cl_var)
(11395200, 11395416)

This does not happen in the a/b example because there you modify foo via a reference. You don't rebind (i.e. assign to) it.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.