Monday, November 16, 2020

, , ,

Example program for super function in python

 super() function in python return the proxy object it's also a temporary object of the superclass and this object help us to access the method of base class.

Super function has two use :-

  • This function Working with Multiple Inheritance
  • Help us to avoid base class name explicitly

Example of super function in python:-

if it use single inheritance then this function help us to refer base class by super()
class Mammal(object):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    
class Dog(Mammal):
  def __init__(self):
    print('Dog has four legs.')
    super().__init__('Dog')
    
d1 = Dog()

OUTPUT

Dog has four legs.
Dog is a warm-blooded animal.

We can also change the name of base class Let see

# changing base class to CanidaeFamily
class Dog(CanidaeFamily):
  def __init__(self):
    print('Dog has four legs.')

    # no need to change this
    super().__init__('Dog')

Well super function in python is an call method for base class via delegation and that is called indirection and this happen at run then time in between this time we can also use the other base classes at different times.

Example program for super() with Multiple Inheritance

class Animal:
  def __init__(self, Animal):
    print(Animal, 'is an animal.');

class Mammal(Animal):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    super().__init__(mammalName)
    
class NonWingedMammal(Mammal):
  def __init__(self, NonWingedMammal):
    print(NonWingedMammal, "can't fly.")
    super().__init__(NonWingedMammal)

class NonMarineMammal(Mammal):
  def __init__(self, NonMarineMammal):
    print(NonMarineMammal, "can't swim.")
    super().__init__(NonMarineMammal)

class Dog(NonMarineMammal, NonWingedMammal):
  def __init__(self):
    print('Dog has 4 legs.');
    super().__init__('Dog')
    
d = Dog()
print('')
bat = NonMarineMammal('Bat')

OUTPUT

super function in python
Example program for super function in python

 

 

Method Resolution Order (MRO)For super() function in python

MRO is use to maintain the order at the persence of the multiple inheritance and ir can also view by using the __mro__ attribute.

>>> Dog.__mro__
(<class 'Dog'>, 
<class 'NonMarineMammal'>, 
<class 'NonWingedMammal'>, 
<class 'Mammal'>, 
<class 'Animal'>, 
<class 'object'>)

0 comments:

Post a Comment