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

Mukund Chavan mukundc at hotmail.com
Thu Sep 22 07:11:25 CEST 2011


That worked. Thank you for the explanation. 

I was trying to take a list of these objects and insert it as a part of a mongo document using the pymongo package. 

But based on what your input and little more reading up, I can use the "__dict__" method to accomplish the same.

Thanks again.

- Mukund


> Date: Thu, 22 Sep 2011 10:58:09 +1000
> From: steve at pearwood.info
> To: tutor at python.org
> Subject: Re: [Tutor] List of Classes with a dictionary within the Class.
> 
> 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
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
 		 	   		  
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110922/61506b5d/attachment-0001.html>


More information about the Tutor mailing list