Access specifier in Python 3 classes
Table of content
- Access specifiers
- Public
- Private
- Protected
- Special methods
Access specifiers
There are three access specifier/modifiers
1. Public : By default the functions and the variables are all public in python.
Note: If there is no preceding _(Single underscore) or __ (Double underscore)
class MyClass:
class_variable = 10 #public variable
def my_method(self):
print("I am public method")
obj1 = MyClass()
obj2 = MyClass()
print(obj1.class_variable)
print(obj2.class_variable)
obj1.my_method()
obj2.my_method()
Output
$ python3 public_accessor.py
10
10
I am public method
I am public method
$
2. Private
To define variable or method private to particular class we use __(Double UnderScore). Private members of class are only accessible within class. (Not in child class also)
class MyClass:
__class_variable = 10 # private variable declared using double underscore
def __my_method(self):
print("I am public method")
def print_class_variable(self):
print(self.__class_variable) # access private variable
obj1 = MyClass()
obj2 = MyClass()
obj2.print_class_variable()
print(obj1.class_variable)
print(obj2.__class_variable)
obj1.my_method()
#obj2.my_method()
Output
$ python3 private_accessor.py
10
Traceback (most recent call last):
File "/Users/code/py/private_accessor.py", line 14, in <module>
print(obj1.class_variable)
AttributeError: 'MyClass' object has no attribute 'class_variable'
$
Private members cannot be accessed through child class.
class MyClass:
__class_variable = 10 # private variable
def __my_method(self):
print("I am public method")
def print_class_variable(self):
print(self.__class_variable)
class InheritedClass(MyClass):
def my_method2(self):
super().__my_method() # private method cannot be called in the child class
in_obj = InheritedClass()
in_obj.my_method2()
Output
$ python3 private_example.py
Traceback (most recent call last):
File "/Users/code/py/private_example.py", line 14, in <module>
in_obj.my_method2()
File "/Users/code/py/private_example.py", line 11, in my_method2
super().__my_method() # as it is private method so we cannot call in the child class
AttributeError: 'super' object has no attribute '_InheritedClass__my_method'
$
3. Protected
Protected members are those members which can be accessed only within package or outside package through child class. To define protected class members we use _ (single underscore).
class MyClass:
_variable = 10 #protected variable
def _my_method(self):
print("I am public method")
def print_class_variable(self):
print(self._variable)
class InheritedClass(MyClass):
def my_method2(self):
super()._my_method()
in_obj = InheritedClass()
in_obj.my_method2()
obj1 = MyClass() #can be accessed within same package
print(obj1._variable)
Output
$ python3 protected_accessor.py
I am public method
10
$