Need help with simple OOP Python question

Stephen Hansen me+list/python at ixokai.io
Mon Sep 5 09:07:45 CEST 2011


On 9/4/11 11:47 PM, Kristofer Tengström wrote:
> Hi, I'm having trouble creating objects that in turn can have custom
> objects as variables. The code looks like this:
> 
> ---------------------------------------------
> 
> class A:
>     sub = dict()

You are sharing this single "sub" dictionary with all instances of your
A class.

If you want to define instance-specific attributes, define them in the
__init__ method, like so:

class A:
    def __init__(self):
        self.sub = dict()

    def sub_add(self, cls):
        obj = cls()
        self.sub[obj.id] = obj

-- 

   Stephen Hansen
   ... Also: Ixokai
   ... Mail: me+list/python (AT) ixokai (DOT) io
   ... Blog: http://meh.ixokai.io/

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 487 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20110905/36985196/attachment.sig>


More information about the Python-list mailing list