Previous: Getters & Setters

Hiding data fields (private data fields) prevent direct modifications of data fields, don’t let the client directly access data fields. This is known as data hiding.

This can be done by defining private data fields. In Python, the private data fields are defined with two leading underscores. You can also define a private method named with two leading underscores.

<aside> 💡

Data Hiding: Private data fields and methods can be accessed within a class, but they cannot be accessed outside the class. We will need: a get method to return its value; a data field to be modified, provide a set method to set a new value.

</aside>

<aside> 💡

We say should, because Python doesn't provide a real shield for the attributes marked as protected.

</aside>

For example, if we want to convert the name attribute from a public to a protected attribute, we just need to change its name from name to _name. If we want to convert the name attribute from a protected to a private attribute, we just need to change its name from _name to __name.

Public Attributes:

# Public attribute
class Rectangle:
    def __init__(self, width, length):
        self.width = width
        self.length = length

def main():
    rect1 = Rectangle(12, 13)
    print(rect1.width, rect1.length)

main()

Output:

12 13

Private Attributes:

# Private attribute
class Rectangle:
    def __init__(self, width, length):
        # Private attributes
        self.__width = width
        self.__length = length

def main():
    rect1 = Rectangle(12, 13)
    print(rect1.__width) 
    print(rect1.__length)

main()

Output: