Encapsulation in Python

Ben Mezger me at benmezger.nl
Thu Mar 10 08:41:25 EST 2016


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

[1] - http://stackoverflow.com/q/4555932

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 801 bytes
Desc: OpenPGP digital signature
URL: <http://mail.python.org/pipermail/python-list/attachments/20160310/1485b41e/attachment.sig>


More information about the Python-list mailing list