Skip to main content

Python 3 Part 11 - Access specifier in Python 3 classes

Access specifier in Python 3 classes 

Table of content 

  1. Access specifiers
    • Public
    • Private
    • Protected
  2. 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
$ 
 

Special Methods/ Dunder Method/ Magic Methods

Methods which have __(Double underscore at start and at end) are special methods. ex: __add__(), __str__(), __init__()

Addition note:

Postfix single _ is used to avoid naming conflicts with python keywords. example, class is a keyword. But if I want to create a variable named class, I would use class_

Thank you folks, if you like my post do check my other posts on Django with Python 3 and Ruby on Rails  on SWE crunch


Most viewed

Ruby on Rails Part 4 - Exception Handling

  Ruby on Rails Part 4 - Exception Handling  Table of content Exception Handling retry raise ensure else  catch and throw Exception classes Exception Handling Enclose the code that could raise an exception with a begin/end block and use rescue clauses to tell Ruby the types of exceptions that you want to handle. The syntax for exception handling : 
 begin  
      #- statements
 rescue OneTypeOfException       #-
 handle the exception rescue AnotherTypeOfException       #- 
handle the exception else       
# Other exceptions
 ensure 
      # ensure block is always executed
 end 
 Everything from begin to rescue is protected 

in the block. 
If an exception occurs during the execution of this block of code, control is passed to the 

block between rescue and end.
 
For each rescue clause in the begin block, Ruby compares the raised Exception against each 

of the parameters of the...