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


Groups > comp.lang.python > #104624 > unrolled thread

Re: Encapsulation in Python

Started byjmp <jeanmichel@sequans.com>
First post2016-03-11 17:42 +0100
Last post2016-03-11 17:42 +0100
Articles 1 — 1 participant

Back to article view | Back to comp.lang.python

This discussion starts older than the indexed window; earlier articles aren't shown. The article labeled Started by below is the oldest one visible, not the original post.


Contents

  Re: Encapsulation in Python jmp <jeanmichel@sequans.com> - 2016-03-11 17:42 +0100

#104624 — Re: Encapsulation in Python

Fromjmp <jeanmichel@sequans.com>
Date2016-03-11 17:42 +0100
SubjectRe: Encapsulation in Python
Message-ID<mailman.27.1457714598.26429.python-list@python.org>
On 03/10/2016 02:41 PM, Ben Mezger wrote:
> Hi all,
>
> I've been studying Object Oriented Theory using Java. Theoretically, all
> attributes should be private, meaning no one except the methods itself
> can access the attribute;
>
> public class Foo {
>      private int bar;
>      ...
>
> Normally in Java, we would write getters and setters to set/get the
> attribute bar. However, in Python, we normally create a class like so;
>
> class Foo(object):
>      bar = 0
>      ...
>
> And we usually don't write any getters/setters (though they exist in
> Python, I have not seen much projects making use of it).
>
> We can easily encapsulate (data hiding) Foo's class using the '_'
> (underscore) when creating a new attribute, however, this would require
> all attributes to have a underscore.
> According to this answer [1], it's acceptable to to expose your
> attribute directly (Foo.bar = 0), so I wonder where the encapsulation
> happens in Python? If I can access the attribute whenever I want (with
> the except of using a underscore), what's the best way to encapsulate a
> class in Python? Why aren't most of the projects not using
> getters/setters and instead they access the variable directly?
>
> Regards,
>
> Ben Mezger

Strictly speaking there is not such things as public/private attributes 
in python. All attributes are public.

'_' is just a (good) convention to tell the class users "don't mess with 
this attribute, don't read it nor write it".

And the python way is to stick to this, trust your users to not use your 
'private' attributes they've been warned.

Short story : in Python we don't hide, we flag.

JM

[toc] | [standalone]


Back to top | Article view | comp.lang.python


csiph-web