The python implementation of the "relationships between classes".

Jerry Zhang jerry.scofield at gmail.com
Thu Nov 10 09:25:35 EST 2011


2011/11/10 Chris Angelico <rosuav at gmail.com>

> On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang <jerry.scofield at gmail.com>
> wrote:
> > Cls_a:
> >     def __init__(self):
> >         self.at1 = 1
> > Cls_b:
> >     def __init__(self):
> >         self.com1 = Cls_a()
> >     def __del__(self):
> >         del self.com1
> > Is it a right implementation for composition?
>
> Yes, except that you don't need to explicitly del it. Python (at
> least, CPython) is reference-counted; your Cls_b object owns a
> reference to the Cls_a object, so (assuming nothing else has a
> reference) that Cls_a will be happily cleaned up when the Cls_b is.
>
> Python doesn't really talk about "composition" etc. It's much simpler:
> everything's an object, and you have references to that object. A
> named variable is a reference to some object. A member on an object
> is, too. Whenever an object is expired, all objects that it references
> lose one reference, and if that was the sole reference, those objects
> get expired too. It's a change of thinking, perhaps, but not a
> difficult one in my opinion; and it's so easy to work with when you
> grok it.
>

Unfortunately there is a difference between composition and aggregation in
my real word, and my application really care this since it is trying to
simulate this real world model, so my system should track this
difference accurately,
otherwise the system may not work well.

For example,
a. the Cls_arm and Cls_body may be composition, but not aggregation. My app
must ensure that " one arm instance only live with one body instance, if
the body instance die, the arm instance must die.
 b. the Cls_auto and the Cls_tyre may be aggregation. "One tyre still can
live even the auto is dead."

Meanwhile, I have a ZODB running, which stores all the living objects.



> ChrisA
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20111110/0786e7cf/attachment-0001.html>


More information about the Python-list mailing list