Initializing Member Variables

Scott Brady Drummonds scott.b.drummonds.nospam at intel.com
Mon Mar 8 18:19:46 CET 2004


Hi, everyone,

I'm a Python novice and just diagnosed a problem that is confusing me.  I
wrote a class that looks like this:

class Keys:
  __dict = {}

  def __init__(self, key):
    self.__dict[key] = key
    print('keys are now: %s' % self.__dict.keys())


When I test this class from my Python interpreter (interactive), I see the
following strange behavior:

>>> import keys
>>> k1 = keys.Keys('1')
keys are now: ['1']
>>> k2 = keys.Keys('2')
keys are now: ['2', '1']
>>> k3 = keys.Keys('4')
keys are now: ['4', '2', '1']
>>>


Maybe this isn't strange for a Python developer, but it sure is for me.  I
thought that the "__dict = {}" line after the class declaration was supposed
to initialize that member variable for each object.  Obviously, that's not
happening.  Instead, that variable is retaining its value from one object to
the next, like a static member variable.  For what it's worth, it seems that
this static variable behavior is not observed when using scalar variables.
Just with dictionaries.

Where have I gone wrong?  What is the purpose of that "initialization" in
the Keys class?  What is the correct was to initialize a class's member
variable and guarantee that it is properly initialized for all objects?

Thanks,
Scott

-- 
Remove ".nospam" from the user ID in my e-mail to reply via e-mail.





More information about the Python-list mailing list