A detailed explanation of the usage and principle of Python super

Time:2020-5-14

This article mainly introduces the usage and principle of Python super. The example code is introduced in detail in this article, which has a certain reference value for your study or work. You can refer to the following for your friends

concept

Super as a built-in function of Python. The main functions are as follows:

  • Allows us to avoid using base classes
  • Follow multiple inheritance to use

example

In the single inheritance scenario, super is generally used to call the base class to implement:
Here is an example:


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 results:

➜ super git:(master) ✗ py super_script.py

Dog has four legs.

Dog is a warm-blooded animal.

Super in multiple inheritance:

Here is an example:


class Animal:
 def __init__(self, animalName):
  print(animalName, '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, NonWingedMammalName):
  print(NonWingedMammalName, "can't fly.")
  super().__init__(NonWingedMammalName)
class NonMarineMammal(Mammal):
 def __init__(self, NonMarineMammalName):
  print(NonMarineMammalName, "can't swim.")
  super().__init__(NonMarineMammalName)
class Dog(NonMarineMammal, NonWingedMammal):
 def __init__(self):
  print('Dog has 4 legs.');
  super().__init__('Dog')

d = Dog()
print('')
bat = NonMarineMammal('Bat')

Output results:


➜ super git:(master) ✗ py super_muli.py
Dog has 4 legs.
Dog can't swim.
Dog can't fly.
Dog is a warm-blooded animal.
Dog is an animal.

Bat can't swim.
Bat is a warm-blooded animal.
Bat is an animal.

Reference documents

https://www.programiz.com/python-programming/methods/built-in/super

The above is the whole content of this article. I hope it will help you in your study, and I hope you can support developepaer more.

Recommended Today

redis day2

persistence mechanism client redis[memory] —–> memory data-data persistence–>disk Redis officially provides two different persistence methods to store data in memory to the hard disk: Snapshot AOF (Append Only File) only appends log files   Snapshot Features:In this way, all data at a certain moment can be written to the hard disk, of course, this is […]