trouble with copy/deepcopy

Peter Otten __peter__ at web.de
Tue May 17 05:03:10 EDT 2005


Alexander Zatvornitskiy wrote:

> Hmm. I don't find definition of "class variable" in manual. I try to test
> it on such a simple test and find that such variable is NOT shared between
> copies:
> 
> class C:
> q=int()
> 
> c1=C()
> c2=C()
> c1.q=5
> c2.q=10
> print c1.q
> #5
> print c2.q
> #10
> 

Your test is flawed:

>>> class C:
...     q = 0 # class variable
...
>>> c = C()
>>> C.__dict__
{'q': 0, '__module__': '__main__', '__doc__': None}
>>> c.__dict__
{}
>>> c.q
0
>>> c.q = 42 # this is stored in the instance, not the class
>>> c.__dict__
{'q': 42}
>>> C.__dict__
{'q': 0, '__module__': '__main__', '__doc__': None}
>>> c.q
42
>>> del c.q
>>> c.q # because C.q is looked up as a fallback, 0 magically reappears
0

Peter




More information about the Python-list mailing list