Saturday, December 7, 2019

[PythonOOPTutorial] 03 Python Access Modifiers

This is the third article of the Python OOP Tutorials.
If you are new to Python, this is how to install Python on your computer.

Basically access modifiers are some sort of keywords used to control or limit the accessibility of attributes, methods, functions, classes, etc... Simply access modifiers define the scope of the components. When it comes to Python there are no specific keywords to define access modifiers; but the number of underscore parameters handles that.

In Python there are 3 access modifier levels.
  • public (no underscore parameters as prefix)
  • private (two underscore parameters as prefix)
  • protected (one underscore parameter as prefix)
Lets learn about those using Python attributes.


Public access modifier:

When an attribute is public, that can be accessed from each and every class. Simply it is visible for all the classes.
There are no underscore parameters as attribute name prefixes.


Private access modifier:

When an attribute is private, that can only be accessed within the same class. When we try to access a private attribute from outside the class it will throw an AttributeError error.
To make an attribute private, we use two underscore parameters as an attribute name prefix.
Since private attributes are not accessible from outside the class, we can write a public method inside the same class to access the private variable.


Protected access modifier:

When an attribute is protected, that can be accessed from the same class or from a sub-class of that class. When we try to access a protected attribute from outside the class which is also not a sub-class it will throw an AttributeError error.
To make an attribute protected, we use one underscore parameter as an attribute name prefix.
From this example you can also understand how to create a sub-class using a super-class. Here class Dog is created by extending the class Animal.


So now you are aware of how to handle access modifier of the Python.
Lets discuss about OOP with Python from the next article.


Cheers...!!

No comments:

Post a Comment