Encapsulation in Python

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Mar 10 09:04:39 EST 2016


On 10/03/2016 13:41, 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;

I suggest that you read 
http://dirtsimple.org/2004/12/python-is-not-java.html and 
http://dirtsimple.org/2004/12/java-is-not-python-either.html

>
> 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).

Python programmers in the main see getters/setters as unneeded, time 
wasting boilerplate.

>
> 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.

No, this is merely a convention that can be worked around if you really 
want to.  The same applies to the use of the double 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?

You have misunderstood.  The '_' is just a convention that says, "this 
is private, please keep your mitts off".  There is nothing to stop a 
programmer from using it.

>
> Regards,
>
> Ben Mezger
>
> [1] - http://stackoverflow.com/q/4555932
>

I suggest that you reread the stackoverflow link that you've quoted, and 
take great notice of the response from Lennart Regebro, even if it has 
been downvoted.

-- 
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence




More information about the Python-list mailing list