Encapsulation unpythonic?

Tim Delaney timothy.c.delaney at gmail.com
Sat Aug 31 13:47:22 EDT 2013


On 1 September 2013 03:31, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote:

> On Fri, 30 Aug 2013 23:07:47 -0700 (PDT), Fabrice Pombet <fp2161 at gmail.com
> >
> declaimed the following:
>
> >well, look at that:
> >
> >a=(1,2)
> >a=2+3 ->a is an object and I have changed its type and value from
> outside. As far as I am concerned this is one hell of an encapsulation
> violation... Could you do this -strictly speaking- in Java or C++?
>
>         There is where your major misunderstanding is...
>
> "a" is a NAME attached (bound) to an object. In the first statement, the
> object is the tuple (1,2). That object was not changed when you execute the
> second statement -- which is taking two integer objects and creating a new
> integer object having a value of '5', and then attaches the NAME "a" to the
> new object. If no other names are bound to the (1,2) object, it will be
> garbage collected.
>

I'll try another way to explain it, using Java terminology(since Fabrice
appears to be familiar with Java).

Object a = Arrays.asList(1, 2);  // a is a reference to the List<Integer>
returned by Arrays.asList
a = Integer.valueOf(2 + 3);  // a is now a reference to the Integer
returned by Integer.valueOf

You have not changed the type of 'a' in any way - you have simply changed
what the name 'a' refers to. This is functionally identical to your Python
code above,except that in Python you do not have to downcast the Object
reference 'a' or use reflection to call methods on it or access it's
members (think of it as Python does reflection automatically for you).

Tim Delaney
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20130901/91a55e9e/attachment.html>


More information about the Python-list mailing list