Like other programming languages such as C#, JAVA, and C++, we don’t have access modifiers like public, private, and protected in python to define the access level restrictions for class members.
By default, all the python class members (variables, methods, etc.) are public. So, we can access all the class members outside of the class. To restrict access, you need to define the class members as private and protected.
To define the class variables or methods as private/protected, you need to prefix the single or double underscore (_) to the variable/method name.
As discussed by default, all the python class members are public, and we can access all the class members outside of the class based on our requirements.
Following is the example of creating a class with required data members and accessing those members outside of the class in python.
When you execute the above python example, you will get the result as shown below.
Generally, the private members access is limited to the defined class. If you try to access the private members outside of the class, you will get an exception.
As discussed, we don’t have any built-in attributes to implement the private variables/methods in the python class. To create the private variables/methods in the python class, you need to prefix the double underscore (__
) to the name of class variables or methods.
Following is the example of creating the private variables and methods in the python class.
If you observe the above example, we prefixed double underscore (__
) to the required variables and methods in the python class to define the private members.
When you execute the above python example, you will get the AttributeError exception as shown below.
The protected members access limited to the defined class and the classes (sub-classes) that are derived from the defined class.
As discussed, in python we don’t have any built-in attributes to implement the protected variables/methods in the python class. To create the protected variables/methods in the python class, you need to prefix the single underscore (_
) to the name of class variables or methods.
Following is the example of creating the protected variables and methods in the python class.
If you observe the above example, we prefixed a single underscore (_
) to the required variables and methods in the python class to define the protected members. We are able to access the protected members from the derived classes.
The above example will return the result as shown below.
This is how you can create the public, private, and protected variables, methods, etc., in python classes based on your requirements.