The python implementation of the "relationships between classes".

Ethan Furman ethan at stoneleaf.us
Thu Nov 10 15:31:23 EST 2011


Benjamin Kaplan wrote:
> You're still misunderstanding Python's object model. del does NOT
> delete an object. It deletes a name. The only way for an object to be
> deleted is for it to be inaccessible (there are no references to it,
> or there are no reachable references to it).
>>>> foo = object()
>>>> bar = foo
>>>> foo
> <object object at 0x01CE14C0>
>>>> bar
> <object object at 0x01CE14C0>
>>>> del foo
>>>> bar
> <object object at 0x01CE14C0>
>>>> foo
> 
> Traceback (most recent call last):
>   File "<pyshell#7>", line 1, in <module>
>     foo
> NameError: name 'foo' is not defined
> 
> 
> There is no way to force the go_to_heaven method to delete the head
> unless you can make sure that all other references to the head are
> weak references. If you need strictly-enforced relationships, Python
> is probably not the right language for the job- you'll be better off
> with C++ or Java.

Having said all that, you could do something like:

class BodyPart(object):
     _alive = True
     def __nonzero__(self):
         return self._alive
     def die(self):
         self._alive = False

class Head(BodyPart):
     "will contain things like Brain, Eyes, etc"
     size = 5

class Body(BodyPart):
     def __init__(self):
         self._head = Head()
     def go_to_heaven(self):
         self._head.die()
         self.die()

John_Doe = Body()

if John_Doe:
     print "John Doe is alive!"
John_Doe.go_to_heaven()
if John_Doe:
     print "uh oh - something wrong"
else:
     print "John Doe is no longer with us"
     print "and his head is %s" % ('alive' if John_Doe._head else 'dead')



More information about the Python-list mailing list