Search This Blog

Wednesday, 15 December 2021

Inheritance in Python

Python Inheritance

how to make your own site

Instead of starting from a scratch, you can create a class by deriving it from a pre-existing class by listing the parent class in parentheses after the new class name.


The child class inherits the attributes of its parent class, and you can use those attributes as if they were defined in the child class. A child class can also override data members and methods from the parent.

Syntax :

class SubClassName (ParentClass1[, ParentClass2, ...]):
    'Optional class documentation string'
    class_suite

example :

class Parent: # define parent class
    parentAttr = 100

    def __init__(self):
       print ("Calling parent constructor")

    def parentMethod(self):
       print ('Calling parent method')

    def setAttr(self, attr):
       Parent.parentAttr = attr

    def getAttr(self):
       print ("Parent attribute :", Parent.parentAttr)

 class Child(Parent): # define child class
    def __init__(self):
       print ("Calling child constructor")

    def childMethod(self):
       print ('Calling child method')

c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method

output of above example  :

Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

In a similar way, you can drive a class from multiple parent classes. multiple inheritance we will learn in next tutorial.

You can use issubclass() or isinstance() functions to check a relationships of two classes and instances.

  • issubclass(sub, sup) boolean function returns True, if the given subclass sub is indeed a subclass of the superclass sup. 
  • isinstance(obj, Class) boolean function returns True, if obj is an instance of class Class or is an instance of a subclass of Class 

Overriding Methods

You can always override your parent class methods. One reason for overriding parent's methods is that you may want special or different functionality in your subclass.

Example :

class Parent: # define parent class
   def myMethod(self):
      print ('Calling parent method')


class Child(Parent): # define child class
   def myMethod(self):
      print ('Calling child method')


c = Child() # instance of child
c.myMethod() # child calls overridden method

output of above example  :

Calling child method

Base Overloading Methods

The following table lists some generic functionality that you can override in your own classes −

MethodDescription 
__init__ ( self [,args...] )Constructor (with any optional arguments)

Sample Call : obj = className(args)
__del__( self )Destructor, deletes an object

Sample Call : del obj
__repr__( self )Evaluatable string representation

Sample Call : repr(obj)
 

__str__( self )
Printable string representation

Sample Call : str(obj)
__cmp__ ( self, x )Object comparison

Sample Call : cmp(obj, x)

Overloading Operators

Suppose you have created a Vector class to represent two-dimensional vectors. What happens when you use the plus operator to add them? Most likely Python will yell at you.


You could, however, define the __add__ method in your class to perform vector addition and then the plus operator would behave as per expectation

Example :

class Vector:
   def __init__(self, a, b):
      self.a = a
      self.b = b

   def __str__(self):
      return 'Vector (%d, %d)' % (self.a, self.b)

   def __add__(self,other):
      return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print (v1 + v2)

output of above example  :

Vector(7,8)

Data Hiding

An object's attributes may or may not be visible outside the class definition. You need to name attributes with a double underscore prefix, and those attributes then will not be directly visible to outsiders.

Example :

class JustCounter:
   __secretCount = 0

   def count(self):
      self.__secretCount += 1
      print (self.__secretCount)

counter = JustCounter()
counter.count()
counter.count()
print (counter.__secretCount)

output of above example  :

1
2
Traceback (most recent call last):
   File "test.py", line 12, in
      print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python protects those members by internally changing the name to include the class name. You can access such attributes as object._className__attrName. If you would replace your last line as following, then it works for you −

.........................
print (counter._JustCounter__secretCount)

output of above example  :

1
2
2

OOPS (Object Oriented Programming) in Python

Python OOPs Concepts

free amp template

Python is an object-oriented programming language. It allows us to develop applications using Object Oriented approach. In Python, we can easily create and use classes and objects.

here is a small introduction of Object-Oriented Programming (OOP) to help you - 

  • Class − A user-defined prototype for an object that defines a set of attributes that characterize any object of the class. The attributes are data members (class variables and instance variables) and methods, accessed via dot notation. 
  • Object − A unique instance of a data structure that is defined by its class. An object comprises both data members (class variables and instance variables) and methods. 
  • Data member − A class variable or instance variable that holds data associated with a class and its objects. 
  • Class variable − A variable that is shared by all instances of a class. Class variables are defined within a class but outside any of the class's methods. Class variables are not used as frequently as instance variables are. 
  • Function overloading − The assignment of more than one behavior to a particular function. The operation performed varies by the types of objects or arguments involved. 
  • Instance variable − A variable that is defined inside a method and belongs only to the current instance of a class. 
  • Inheritance − The transfer of the characteristics of a class to other classes that are derived from it. 
  • Polymorphism - Polymorphism is made by two words "poly" and "morphs". Poly means many and Morphs means form, shape. It defines that one task can be performed in different ways
  • Encapsulation - Encapsulation is also the feature of object-oriented programming. It is used to restrict access to methods and variables. In encapsulation, code and data are wrapped together within a single unit from being modified by accident.
  • Data Abstraction - Abstraction is used to hide internal details and show only functionalities. Abstracting something means to give names to things, so that the name captures the core of what a function or a whole program does.
  • Instance − An individual object of a certain class. An object obj that belongs to a class Circle, for example, is an instance of the class Circle. 
  • Instantiation − The creation of an instance of a class. 
  • Method − A special kind of function that is defined in a class definition. 
  • Operator overloading − The assignment of more than one function to a particular operator. 

DIY Game Console Using SSD1306 OLED Display and NodeMCU/Arduino UNO

DIY Game Console Using OLED Display and NodeMCU/Arduino UNO Have you ever wondered if you could create your own handheld game console? In th...