Encapsulation in Python

dieter dieter at handshake.de
Fri Mar 11 04:29:25 EST 2016


Ben Mezger <me at benmezger.nl> writes:

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

If you expose publicly both a "setter" and a "getter" what is the gain
not to make the attribute public in the first case (other than
cluttering up your code).

I very much like the "Eiffel" view that there should be no
distinction between an attribute access and the call of a zero
parameter method. Thus, there are no "getter"s at all.
Unlike "Python", "Eiffel" is very interested in encapsulation:
thus attributes can be private, limited to derived classes or public --
and they can be readonly.

"Python" is much less interested in encapsulation - and more in
the ability to quickly get a solution to a practical problem.


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

And it is only a hint towards users of the class. Nothing forces
a piece of code to use it as public.

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

If you are really interested to enforce Java encapsulation policies
(access to attributes via "getter/setter" only), you will need
to use your own "metaclass".

The "metaclass" has a similar relation to a class as a class to
an instance: i.e. it constructs a class. During the class construction,
your "metaclass" could automatically define "getter/setter" methods
for declared class attributes and hide the real attributes (maybe
by prefixing with "__").
Of course, class level (non-method) attributes are rare; most
attributes of Python instances are not defined at the class level
but directly at the instance level - and the metaclass would
need to define "__setattr__" and "__getattribute__" to control access
to them.

However, I think you should not use Python in cases where you
need strong encapsulation.




More information about the Python-list mailing list