Jeremy Lynch wrote:
> Hello,
> 
> Learning python from a c++ background. Very confused about this:
> 
> ============
> class jeremy:
>       list=[]
>               def additem(self):
>               self.list.append("hi")
>               return
> 
> temp = jeremy()
> temp.additem()
> temp.additem()
> print temp.list
> 
> temp2 = jeremy()
> print temp2.list
> ==============
> The output gives:
> ['hi','hi']
> ['hi','hi']
> 
> Why does adding items to one instance produce items in a separate
> instance? Doesn't each instance of jeremy have its' own "list"?
> 
> Many thanks for clearing up this newbie confusion.
> 
> Jeremy.
> 

In this code, "list" (bad name) is a class attribute and all therefor in 
all instances, the "list" attribute is reference to the class attribute 
unless otherwise assigned, as in __init__.

For instance, try:


temp = jeremy()
temp.additem()
temp.additem()
print temp.list

temp2 = jeremy()
temp2.list = [1,2,3]
print temp.list, temp2.list, jeremy.list


And see which ones look the same (same reference) or look different.

James
-- 
http://mail.python.org/mailman/listinfo/python-list

Reply via email to