This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: The attribute's action of an object is not correct.
Type: behavior Stage:
Components: None Versions: Python 3.0
process
Status: closed Resolution:
Dependencies: Superseder:
Assigned To: Nosy List: Kozyarchuk, Yong yang
Priority: normal Keywords:

Created on 2009-03-31 11:27 by Yong yang, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (3)
msg84765 - (view) Author: edmundy (Yong yang) Date: 2009-03-31 11:27
The following is the test code.

class C1:
	myurl = []	
	def test(self):
		url = [5,6,7]
		self.myurl.extend(url)		
def testv():
	c = C1()
	c.test()
	print(c.myurl)
	
i = 0
while i<10 :
	testv()
	i = i+1

The output is :

[5, 6, 7]
[5, 6, 7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 
7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 
7, 5, 6, 7]
[5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 7, 5, 6, 
7, 5, 6, 7, 5, 6, 7]

The myurl of class C1 is not set to [] when a new object is created.
All objects use the same memory.
msg84791 - (view) Author: Maksim Kozyarchuk (Kozyarchuk) Date: 2009-03-31 14:56
AFAIK, This is expected behavior.  myurl is a class attribute if you
want it to be different per instance you should re-initialize it in the
__init__ method.  See below. 

>>> class C1(object):
...     def __init__(self):
...             self.myurl = []
...     def test(self):
...             self.myurl.extend([5,6,7])
...
[44085 refs]
>>> def testv():
...     c = C1()
...     c.test()
...     print(c.myurl)
...
[44108 refs]
>>> for i in range(10):
...     testv()
...
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[5, 6, 7]
[44119 refs]
msg85003 - (view) Author: edmundy (Yong yang) Date: 2009-04-01 13:05
Thanks a lot!
Kozyarchuk.

I have thought the self.myurl should be the object variable, not class 
variable.
The class variable really is confusing.

Why do they like that?
History
Date User Action Args
2022-04-11 14:56:47adminsetgithub: 49870
2009-04-01 13:05:28Yong yangsetstatus: open -> closed

messages: + msg85003
2009-03-31 14:56:32Kozyarchuksetnosy: + Kozyarchuk
messages: + msg84791
2009-03-31 11:27:23Yong yangcreate