Encapsulation

Encapsulation is a term that is used to refer to the ability of a class to restrict the access to its members only through the public interfaces exposed by the object. The concept of encapsulation helps us in just working on the details about what we want to do with the object and not about how the object will deal with the changes internally.

In Python, the encapsulation is not strictly enforced, in that we do not have the support of access modifiers, such as private, public, and protected, which can be used to strictly control the access to a particular member inside a class.

However, Python does support encapsulation with the help of name mangling, which can be used to restrict direct access to a particular property of a class by prefixing the property name with __(double underscores). The following code snippet shows an example of this:

class PyOOP:
__name = None

def __init__(self, name):
self.__name = name

def get_name():
return self.__name

pobj = PyOOP('Joe')
print(pobj.__name)

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'PyOOP' object has no attribute '__name'

As we can see from the preceding code example, an attempt to access the __name property of PyOOP object raised an AttributeError because the property was identified as private in the class.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
52.14.151.45