简体   繁体   中英

class variables v/s instance variables in python

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 ?

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 (ie assign to) it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM