Using classes in python

Colin J. Williams cjw at sympatico.ca
Fri Oct 27 08:32:28 EDT 2006


trevor lock wrote:
> Hello,
> 
> I've just started using python and have observed the following :
> 
> class foo:
>     a=[]
>     def __init__(self, val):
>             self.a.append ( val )
>     def getA(self):
>             print self.a
>             return self.a
> 
> z = foo(5)
> y = foo(4)
> z.getA()
>  >> [5, 4]
> 
> I was expecting that everytime I created an instance of the class that a 
> unique dictionary was also created, however it seems that only one 
> dictionary is created.
> 
> How can I create a new dictionary for each instance?
You do already, as the little script below illustrates:

# checkInstance.py

class A(object):
   def __new__(cls, n):
     return object.__new__(cls)
   def __init__(self, n):
     self.a= n


a1= A(21)
a2= A(22)
print a1.a, a2.a, a1.__dict__ is a2.__dict__

Colin W.
> 
> Thanks,
> Trevor.
> 
> ------------------------------------------------------------------------
> All-new Yahoo! Mail 
> <http://us.rd.yahoo.com/evt=43256/*http://advision.webevents.yahoo.com/mailbeta>- 
> Fire up a more powerful email and get things done faster.
> 




More information about the Python-list mailing list