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 6 - Blocks , lambda, procs and closure

 Blocks , lambda, procs  and closure Table of content  1. Blocks 2. Lambda 3. Procs 4. Closure Blocks  Ruby blocks are little anonymous functions that can be passed into methods. Blocks are enclosed in a do-end statement or between brackets {} 
. Blocks can have multiple arguments
. The argument names are defined between two pipe | characters. Blocks are typically used with ‘each’ method which iterates over a list. Syntax of block using {} ['List of items'].each { | block arguments|  block body }  Syntax of block using do-end ['List of items'].each do | block arguments |      # block body end Example of block declared as do-end with each method.   [ 1 , 2 , 3 ].each do |num| puts num end     Output   $ ruby block_with_each.rb 1 2 3 $    Blocks can also be saved in variables or passed as argument to another function.   yield is a Ruby keyword that is used to call a block. When you use the yield keyword, the code inside the block will run. Example of saving a bl