Simple questions on use of objects (probably faq)
bruno at modulix
onurb at xiludom.gro
Thu Mar 9 04:07:58 EST 2006
Brian Elmegaard wrote:
> bruno at modulix <onurb at xiludom.gro> writes:
>
>
>>Now how you could do it the OO way (Q&D, not really tested):
>
>
> Something goes wrong in my 2.3
So it's time to move to 2.4x !-)
What is "going wrong" exactly ?
> when I change the syntax to
> _add_instance=classmethod(_add_instance).
> If I understand this correctly the class is keeping track of the
> instances of itself.
Yeps.
> The class is extendible and has all the needed
> methods. This means that any global lists can be
> avoided.
Yeps too. This is called "encapsulation".
But this also means you only have one list of instances - which may or
may not be ok for what you're trying to do. Note that there are possible
workarounds, like using a dict of lists:
class Foo(object):
_instance_lists = {}
def __init__(self, x, list_id):
self.x = x # no, you won't avoid it
self._add_instance(self, list_id)
@classmethod
def _add_instance(cls, instance, list_id):
cls._instance_lists.setdefault(list_id, []).append(instance)
@classmethod
def get_instances(cls, list_id):
return cls._instance_lists[list_id].[:]
# now you need to add the list_id parameter to all others classmethods
Also, if you intend to use such a solution (with or without multiple
lists), you may want to add a classmethod to delete instances from the
list(s).
--
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"
More information about the Python-list
mailing list