Introductory Concept of Abstraction in Python
* In languages like Java , there are several keywords like
private , public and protected in order to implement the various levels of
abstraction . These keywords are called as Access
Specifiers .
* In Python , such kind of Access Specifiers are not available .
* Everything written inside the class comes under the category of public – that means all the objects , methods , variables present within any class in Python can be considered to be coming under Public Category which means that everything which is written inside a class is available outside the class to other people .
* Suppose , one does not want to make a variable outside the class or to other members inside the class , then we can write the variable with two double scores before it as : _var . This is like a private variable in Python .
* In the following example , 'y' is a private variable since it is written as : __y
class MyClass:
def
_init_(self):
self.__y = 3
* Now , it is not possible to access the variables from within the class or outside of the class as :
m = MyClass()
print(m.y)
* The preceding print() statement displays an error message as : AttributeError :'MyClass' object has no attribute 'y' .
* Even though one can not access the private variable in this way .. however , it is possible to access it in the format :
instancename.__Classname_var
* This means that we are using the Classname differently to access
the private variable . This concept is known as name mangling . In name mangling , one needs to use one underscore
before the classname and two underscores after the classname . Like this , using
the names differently to access the private variables is called as name mangling .
The same statement can be written inside the method as :
print(self._MyClass_z) . When we use single underscore before a variable as _var , then that variable or object will not be imported into other files .
No comments:
Post a Comment