Encapsulation in Python

Ian Kelly ian.g.kelly at gmail.com
Fri Mar 11 10:08:45 EST 2016


On Fri, Mar 11, 2016 at 2:29 AM, dieter <dieter at handshake.de> wrote:
> 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.

Pythonically, one would use a property to do this. You don't need
anything so advanced as a metaclass. Using either approach though,
there is no place you can hide the real attributes where the caller
isn't capable of getting at them.



More information about the Python-list mailing list