Using classes in python

Éric Daigneault daigno at gmail.com
Wed Oct 25 17:15:47 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.
Yep...  Normal...

I just asked the question here a couple days ago...  I felt like I 
bumbed into a wall, even reported as a bug...

Turned out Guido and his bunch cleaned the window so nicely I bumbed 
right into it.....  All I had to do is open the door :-)

http://youtube.com/watch?v=6E7urz5rXVc&mode=related&search=

No really, jokes appart here goes :

"a" here is a *class* attribute.  When you create a new *Instance* of a 
class you can access the atttribute of the class.  But what you need is 
a Instance attribute...

Try this

class toto:
    list = []
    def __init__(self,
                 val):
        self.list = []
        self.list.append(val)
        toto.list.append(val)
       
    def getList(self):
        return self.list
   
    def getClassList(self):
        return toto.list
   
if __name__ == '__main__':
    toto1 = toto(6)
    titi1 = toto("Patate")
   
    print toto1.getList()
    print titi1.getList()
    print toto1.getClassList()
    print titi1.getClassList()


running this gives :

[6]
['Patate']
[6, 'Patate']
[6, 'Patate']

Therefore creating an instance of toto creates *two* instances of the 
list attribute.  The object instance overshadowing the class attribute...
>
> How can I create a new dictionary for each instance?
Simple answer is therefore to place variable declaration in the __init__ 
method...
>
> Thanks,
> Trevor.




More information about the Python-list mailing list