Encapsulation in Python

jmp jeanmichel at sequans.com
Fri Mar 11 11:42:49 EST 2016


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




More information about the Python-list mailing list