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

No comments:

Post a Comment

how to implement YOLOv3 using Python and TensorFlow

Object Detection with YOLOv3 Introduction YOLOv3 (You Only Look Once version 3) is a real-time object detection algorithm that can detect ob...