Initializing Member Variables

Robert Brewer fumanchu at amor.org
Mon Mar 8 18:44:41 CET 2004


Scott Brady Drummonds wrote:
> class Keys:
>   __dict = {}
> 
>   def __init__(self, key):
>     self.__dict[key] = key
>     print('keys are now: %s' % self.__dict.keys())
> 
> 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.  

This is normal, and someday you will use this feature to your advantage.
:) Your immediate issue is this: putting __dict = {} in the *class*
declaration does not make a separate attribute for each *instance*; it
merely makes a single attribute for the class. To create an attribute
for the class, you must write code which--surprise, surprise--adds that
attribute to the *instance*. For example, you might modify your code to:

class Keys:
    __dict = {}

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


I'm going to be very explicit, now, so pay attention to each word: the
new line, "self.__dict = {}" creates a new dictionary, binds it to the
name "__dict", making it an attribute of the object named "self".

Without that extra line, Python will examine the object named "self",
find it has no instance attribute named "__dict", then examine the
*class* of the object named "self", find an attribute named "__dict",
and use that, which results in (behaves like) a static attribute for the
class.


Hope that helps.


Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org




More information about the Python-list mailing list