[Tutor] Keeping a list of attributes of a certain type
Guilherme P. de Freitas
guilherme at gpfreitas.com
Thu Jan 14 05:15:21 CET 2010
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
<guilherme at 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
>
--
Guilherme P. de Freitas
http://www.gpfreitas.com
More information about the Tutor
mailing list