(You top-posted, which puts your two comments out of order. Now the solution comes before the problem statement)

Guilherme P. de Freitas wrote:
Ok, I got something that seems to work for me. Any comments are welcome.


class Member(object):
    def __init__(self):
        pass


class Body(object):
    def __init__(self):
        self.members = []

    def __setattr__(self, obj, value):
        if isinstance(value, Member):
            self.members.append(obj)
            object.__setattr__(self, obj, value)
        else:
            object.__setattr__(self, obj, value)

    def __delattr__(self, obj):
        if isinstance(getattr(self, obj), Member):
            self.members.remove(obj)
            object.__delattr__(self, obj)
        else:
            object.__delattr__(self, obj)



john = Body()
john.arm = Member()
print(john.members)
del john.arm
print(john.members)


On Wed, Jan 13, 2010 at 6:24 PM, Guilherme P. de Freitas
<guilhe...@gpfreitas.com> wrote:
Hi everybody,

Here is my problem. I have two classes, 'Body' and 'Member', and some
attributes of 'Body' can be of type 'Member', but some may not. The
precise attributes that 'Body' has depend from instance to instance,
and they can be added or deleted. I need any instance of 'Body' to
keep an up-to-date list of all its attributes that belong to the class
'Member'. How do I do this?

Best,

Guilherme

--
Guilherme P. de Freitas
http://www.gpfreitas.com

If this is a class assignment, you've probably got the desired answer. But if it's a real-world problem, there are tradeoffs, and until those are known, the simplest solution is usually the best. Usually, what's desired is that the object behaves "as if" it has an up-to-date list of...

If order of the list doesn't matter, I'd consider simply writing a single method, called 'members' which does a list comprehension of the object's attributes, calculating the list when needed. Then use a decorator to make this method look like a read-only data attribute (untested):

class Body (object):
    @property
     def members(self):
            return  [obj for .....   if .... ]

DaveA



_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor

Reply via email to