Multiple instances and wrong parental links

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun Jan 2 02:29:53 EST 2011


On Sat, 01 Jan 2011 17:59:33 -0800, Josh English wrote:

> I have hit yet another wall. I am dynamically creating a class and then
> creating instances of that class. The class relies on a second class to
> store a list of objects. (This is simplified from the the original by a
> factor of about 20.

Sounds like it's about 40 times too complex then: aim for something about 
half the complexity of this "simplified" version.


> The real program is trying to create a Python object
> around an XML definition object.)
> 
> Here's the code:
> 
> ## OPTION ONE for class: ElementList
> ### Not really a list, but a wrapper that behaves like a list class
> ElementList(object):
>     def __init__(self, parent, name):
>         self._parent = parent
>         self._name = name


Doesn't behave much like a list for me :)


> def MakeWrapper(checker, _addNameAsAttribute = False ):
>     ## OPTION TWO for class: ElementList
>     class Wrap(object):
>         ## OPTION THREE for class: Elementlist
>         def __init__(self, name):
>             self._name = name
>             setattr(Wrap, 'stuff', ElementList(self, 'test'))
>     Wrap.__name__= checker.title()
>     return Wrap


Your problem is that all the instances from a MakeWrapper class share the 
same "stuff" attribute, which is attached to the class Wrap. What you 
probably want is:

setattr(self, 'stuff', ElementList(self, 'test'))

instead. What you *need* is to rethink this complicated strategy for a 
simpler one.


-- 
Steven



More information about the Python-list mailing list