Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #15537

Re: The python implementation of the "relationships between classes".

References <CANVwdDr-6x8bt4iNL+Q=jZ7+edk7XbR2K_LeJC3Z60qy=vVFQA@mail.gmail.com> <CAPTjJmoOBTiRE8vUNz_xQcwDZA6gazG1fAMkFfhPMomtAKtp6w@mail.gmail.com> <CANVwdDr6qBueBGXykLrhH+MLiwyozD_U1+YRBnrWNfge0=uvDQ@mail.gmail.com>
Date 2011-11-11 01:09 +1100
Subject Re: The python implementation of the "relationships between classes".
From Chris Angelico <rosuav@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.2597.1320934151.27778.python-list@python.org> (permalink)

Show all headers | View raw


On Fri, Nov 11, 2011 at 12:58 AM, Jerry Zhang <jerry.scofield@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.

ChrisA

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: The python implementation of the "relationships between classes". Chris Angelico <rosuav@gmail.com> - 2011-11-11 01:09 +1100

csiph-web