[Python] Reasons for overriding using super ()

About this article

Looking at the Django source code, I found many that used super () to override classes. Here's what super () is and what's different from overriding it without using it.

What is an override

To define a method with the same name as the base class in the derived class. You can add or change functions to the methods of the base class.

Define the base class


#Base class
class Coffee(object):
    def __init__(self, color, fragrance, price, taste, elapsed_time):
        self.color = color
        self.fragrance = fragrance
        self.price = price
        self.satisfaction = ((taste + fragrance) * price) - elapsed_time
        
    def drink(self):
        print(f'Satisfaction{self.satisfaction}Drink Hoffy of the point')


coffee = Coffee('brown', 10, 200, 10, 300)
coffee.drink() # <---Drink Hoffy with 3700 satisfaction

Now that we have defined the base class, let's create a derived class below with and without super (). (Both have the same function)

Override base class (do not use super ())

Let's create a class that inherits the Coffee class and overrides the method.


#After taking over Coffee, I want to expand the functionality! !!

class Override(Coffee):
    #If you override it normally, the processing of the base class will be invalidated, so if you want to extend the processing, you need to write the same processing as the base class.
    def __init__(self, color, fragrance, price, taste, elapsed_time, size):
        self.color = color
        self.fragrance = fragrance
        self.price = price
        self.satisfaction = ((taste + fragrance) * price) - elapsed_time + size * 55
        self.size = size
        
    def size_up(self):
        self.price += 100
        self.size += 1
        print(f'size is{self.size}Became! Instead the price went up...')
        
    #The base class methods also have to be defined again from scratch
    def drink(self):
        print(f'Satisfaction{self.satisfaction}Drink Hoffy of the point')
        print(f'size is{self.size}Was a little too much...')

#Execution result Normal override
override = Override('brown', 10, 200, 10, 300, 10)
override.drink() # <---Drink Hoffy with 4250 points of satisfaction,I wonder if size 10 was a little too much..
override.size_up() # <---The size is now 11! Instead the price went up....

Overridden the __init __ () and drink () methods of the base class. If you override it normally, the processing of the base class will be invalidated, so if you simply want to extend the processing, you need to write the same processing as the base class, which will result in redundant code.

Override with super ()


class SuperOverride(Coffee):
    #By calling the constructor of the base class with the Super function, you don't have to write the initialization code anymore.
    def __init__(self, color, fragrance, price, taste, elapsed_time, size):
        super().__init__(color, fragrance, price, taste, elapsed_time,)
        self.size = size
        
    def size_up(self):
        self.price += 100
        self.size += 1
        print(f'size is{self.size}Became! Instead the price went up...')
        
    #Base class methods are called, so there is redundancy
    def drink(self):
        super().drink()
        print(f'size is{self.size}Was a little too much...')

#Execution result super()Override with function
super_override = SuperOverride('brown', 10, 200, 10, 300, 10)
super_override.drink() # <---Drink Hoffy with 4250 points of satisfaction,I wonder if size 11 was a little too much... 
super_override.size_up() # <---The size is now 12! Instead the price went up...

The value passed to the parameters (color, fragrance, price, taste, elapsed_time) of the __init__ method of SuperOverride is assigned to the parameters of the base (Coffee) class and initialized. Since the base class method is called entirely with super (), satisfaction is also inherited.

Note that super (). Drink () is synonymous with super (SuperOverride self) .drink (). In other words, you can write super (own class, self) .method name, but you can omit it as in the above code.

Summary

As mentioned above, super () can be used when you want to extend the process after inheriting the method of the base class, so that you can save the description and make the code easier to read.

Recommended Posts

[Python] Reasons for overriding using super ()
Python #function 2 for super beginners
Python for super beginners Python #functions 1
Python #list for super beginners
Python for super beginners Python # dictionary type 1 for super beginners
Python #index for super beginners, slices
[TouchDesigner] Tips for for statements using python
Python #len function for super beginners
[Python] Multiplication table using for statement
Python #Hello World for super beginners
Python for super beginners Python # dictionary type 2 for super beginners
Notes for using OpenCV on Windows10 Python 3.8.3.
Python development environment for macOS using venv 2016
[50 counts] Key transmission using Python for Windows
[python, multiprocessing] Behavior for exceptions when using multiprocessing
Let's put together Python for super beginners
Tips for using python + caffe with TSUBAME
2016-10-30 else for Python3> for:
python [for myself]
Start using Python
Scraping using Python
vprof --I tried using the profiler for Python
Python for super beginners Python for super beginners # Easy to get angry
Python pandas: Search for DataFrame using regular expressions
Get note information using Evernote SDK for Python 3
Refined search for Pokemon race values using Python
Easy understanding of Python for & arrays (for super beginners)
Let's make a module for Python using SWIG
About Python external module import <For super beginners>
Let's analyze Covid-19 (Corona) data using Python [For beginners]
About Python for loops
Initial settings for using Python3.8 and pip on CentOS8
Operate Redmine using Python Redmine
Searching for pixiv tags and saving illustrations using Python
Extendable skeletons for Vim using Python, Click and Jinja2
Python basics ② for statement
Fibonacci sequence using Python
Directory structure for test-driven development using pytest in python
[Python] Super useful debugging
Method overriding and super
Data analysis using Python 0
[Python] Class inheritance (super)
About Python, for ~ (range)
Data cleaning using Python
python textbook for beginners
Explore Alibaba Cloud Function Compute for DevOps using Python 3.0
Refactoring tools for Python
Using Python #external packages
WiringPi-SPI communication using Python
python for android Toolchain
Age calculation using python
Search Twitter using Python
Python # How to check type and type for super beginners
Name identification using python
Notes using Python subprocesses
Memo for building a machine learning environment using Python
Try using Tweepy [Python2.7]
OpenCV for Python beginners
python memorandum super basic
[Introduction to Python] How to write repetitive statements using for statements
Install Python (for Windows)