Skip to content Skip to sidebar Skip to footer

Understanding Data Encapsulation In Python

I am reading up on how we ensure data encapsulation in python.One of the blog says 'Data Encapsulation means, that we should only be able to access private attributes via getters a

Solution 1:

Data encapsulation is slightly more general than access protection. name and build_year are encapsulated by the class Robot regardless of how you define the attributes. Python takes the position that getters and setters that do nothing more than access or assign to the underlying attribute are unnecessary.

Even using the double-underscore prefix is just advisory, and is more concerned with preventing name collisions in subclasses. If you really wanted to get to the __build_year attribute directly, you still could with

# Prefix attribute name with _Robotx._Robot__build_year = 1993

A better design in Python is to use a property, which causes Python to invoke a defined getter and/or setter whenever an attribute is defined directly. For example:

classRobot(object):def__init__(self, name, by):
        self.name = name
        self.build_year = by

    @propertydefname(self):
        returnself._name

    @name.setter
    defname(self, newname):
        self._name = newname

    @propertydefbuild_year(self):
        returnself._build_year

    @build_year.setter
    defbuild_year(self, newby):
        self._build_year = newby

You wouldn't actually define these property functions so simply, but a big benefit is that you can start by allowing direct access to a name attribute, and if you decide later that there should be more logic involved in getting/setting the value and you want to switch to properties, you can do so without affecting existing code. Code like

x = Robot("bob", 1993)
x.build_year = 1993

will work the same whether or not x.build_year = 1993 assigns to build_year directly or if it really triggers a call to the property setter.

Solution 2:

About source code: sometimes you supply others with compiled python files that does not present the source, and you don't want people to get in mess with direct attribute assignments.

Now, consider data encapsulation as safe guards, last point before assigning or supplying values:

You may want to validate or process assignments using the sets, to make sure the assignment is valid for your needs or enters to the variable in the right format, (e.g. you want to check that attribute __build_year is higher than 1800, or that the name is a string). Very important in dynamic languages like python where a variable is not declared with a specific type.

Same goes for gets. You might want to return the year as a decimal, but use it as an integer in the class.


Yes, your example is a basic data encapsulation.

Post a Comment for "Understanding Data Encapsulation In Python"