Figuring out what class instance contains you
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Fri Apr 4 02:17:34 EDT 2008
En Fri, 04 Apr 2008 00:41:19 -0300, Alex VanderWoude
<alex at computronix.com> escribió:
> Consider the following module:
>
> ================================
> class NewDict(dict):
> parent = None
>
> def __setitem__(self, key, value):
> print "My parent is", self.parent
> super(NewDict, self).__setitem__(key, value)
>
> class Zero(object):
> children = NewDict()
>
> def __init__(self):
> self.children.parent = self
>
> class One(Zero):
> pass
>
> class Two(One):
> pass
>
> a = One()
> a.children["spam"] = "baked beans"
> b = Two()
> b.children["eggs"] = "bacon"
> ================================
>
> When the above module is executed, the output looks something like this:
>
> My parent is <__main__.One object at 0x00BA27B0>
> My parent is <__main__.Two object at 0x00B9D170>
>
> ...which is great, just what I wanted. Each dictionary instance reports
> correctly which object instance is its container.
But only if you create a single instance of each class, because "children"
is a class attribute (behaves as it were shared among all instances).
Then you need an instance attribute, initialized in __init__. So why not
set the parent at this time?
py> class NewDict(dict): pass
...
py> class Zero(object):
... def __init__(self):
... self.children = NewDict()
... self.children.parent = self
...
py> class One(Zero):
... pass
...
py> class Two(One):
... pass
...
py> a = One()
py> a.children["spam"] = "baked beans"
py> b = Two()
py> b.children["eggs"] = "bacon"
py> c = Two()
py> c.children["foo"] = "bar"
py> print a.children.parent is a
True
py> print b.children.parent is b
True
py> print c.children.parent is c
True
> However, I would like to find some automagic way of having NewDict
> figure out what object instance it is on without resorting to having the
> container class instance poke a reference to itself into the NewDict
> instance (i.e. the line in Zero.__init__()).
Unless there are more contrains that you haven't told us, the above
example looks as the simplest approach.
--
Gabriel Genellina
More information about the Python-list
mailing list