InterviewSolution
| 1. |
Does Python support data encapsulation? |
|
Answer» As per the principles of object oriented programming, data encapsulation is a mechanism by which instance attributes are prohibited from direct access by any environment outside the class. In C++ / Java, with the provision of access control keywords such as public, private and protected it is easy to enforce data encapsulation. The instance variables are usually restricted to have private access, though the methods are publicly accessible. However, Python doesn’t follow the doctrine of controlling access to instance or method attributes of a class. In a way, all attributes are public by default. So in a strict sense, Python doesn’t support data encapsulation. In the following example, name and age are instance attributes of User class. They can be directly manipulated from outside the class environment. >>> class User: def __init__(self): self.name='Amar' self.age=20 >>> a=User() >>> a.name 'Amar' >>> a.age 20 >>> a.age=21Python even has built-in functions getattr() and setattr() to fetch and set values of an instance ATTRIBUTE. >>> getattr(a, 'name') 'Amar' >>> setattr(a,'name','Ravi') >>> a.name 'Ravi'Having said that, Python does have means to emulate private keywords in Java/C++. An instance VARIABLE prefixed with ‘__’ (double underscore) behaves as a private variable – which means direct access to it will raise an exception as below: >>> class User: def __init__(self): self.__name='Amar' self.__age=20 >>> a=User() >>> a.__name Traceback (most recent call last): File "<pyshell#18>", line 1, in <module> a.__name AttributeError: 'User' object has no attribute '__name'However, the double underscore prefix doesn’t make price truly private (as in case of Java/C++). It merely performs name mangling by internally renaming the private variable by ADDING the "_ClassName" to the front of the variable. In this case, variable named "__name" in Book class will be MANGLED in “_User__name” form. >>> a._User__name 'Amar'Protected member is (in C++ and Java) accessible only from within the class and its subclasses. Python accomplishes this behaviour by convention of prefixing the name of your member with a single underscore. You’re telling others “don’t TOUCH this, unless you’re a subclass”. |
|