[Tutor] List of Classes with a dictionary within the Class.

Steven D'Aprano steve at pearwood.info
Thu Sep 22 02:58:09 CEST 2011


Mukund Chavan wrote:
> Hi,
> 
> I was trying to get a list of Class Objects. 
> The Class itself has string fields and a dictionary that is initialized as a part of the "__init__"

No it doesn't. It has a dictionary that is initialised *once*, when the 
class is defined. From that point on, every instance just modifies the 
same shared dictionary:

> class Person(object):
>    """__init__() functions as the class constructor"""
>    personAttrs={"'num1":"","num1":""}

This is a "class attribute", stored in the class itself, and shared 
between all instances.


>    def __init__(self, name=None, job=None, quote=None, num1=None, num2=None):
>       self.name = name
>       self.job = job
>       self.quote = quote
>       self.personAttrs["num1"]=num1
>       self.personAttrs["num2"]=num2

This merely modifies the existing class attribute. You want something 
like this instead:

class Person(object):
     def __init__(self, name=None, job=None, quote=None,
                  num1=None, num2=None
                 ):
         self.name = name
         self.job = job
         self.quote = quote
         self.personAttrs = {'num1': num1, 'num2': num2}

This creates a new dictionary for each Person instance.

But why are you doing it that way? Each Person instance *already* has 
its own instance dictionary for storing attributes. You don't need to 
manage it yourself -- just use ordinary attributes, exactly as you do 
for name, job, and quote.

class Person(object):
     def __init__(self, name=None, job=None, quote=None,
                  num1=None, num2=None
                 ):
         self.name = name
         self.job = job
         self.quote = quote
         self.num1 = num1
         self.num2 = num2



-- 
Steven


More information about the Tutor mailing list