Dict in Class Problem

Steve Holden sholden at holdenweb.com
Tue Oct 8 09:06:30 EDT 2002


"Sebastian Haas" <haas at ems-wuensche.com> wrote in message
news:3DA2F0C2.8060801 at ems-wuensche.com...
> Hello NG,
>
> i have a little problem in Python.
>
> code:
>
> #! /usr/bin/python
>
> class CTest:
> dicton = {}
>
> first = CTest()
> secon = CTest()
>
> first.dicton['test'] = "RE"
> secon.dicton['test'] = "BE"
>
> print first.dicton['test']
>
> Why is the output "BE", why not "RE".
>
> With
> first = CTest()
> secon = CTest()
> i get 2 new object, 2 objects that differs, or not??
>
> The Keys are the same, okay, but i have 2 different objects (with 2
> different dictionarys).
>
You might think that, but actually because you create the dictionary in
class scope it is common to all instances. What you really need is:

class CTest:
  def __init__(self):
    self.dicton = {}

This makes "dicton" an instance variable, and each instance gets its own
copy.

> I hope for help and thanks for help.
>
I hope this makes things clearer for you.

regards
-----------------------------------------------------------------------
Steve Holden                                  http://www.holdenweb.com/
Python Web Programming                 http://pydish.holdenweb.com/pwp/
Previous .sig file retired to                    www.homeforoldsigs.com
-----------------------------------------------------------------------






More information about the Python-list mailing list