Python: [Inheritance] Reuse superclass constructors in subclasses

I'm new to Python. I have investigated inheritance, so I will keep it as a memorandum.

Execution environment

Windows7 64bit Python 2.7

Reuse of parent class constructor

About classes Acquisition of super class

classTest.py


# -*- coding: utf-8 -*-

class BaseClass(object):    #Inheriting the object class

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

    def sum(self):
        return self.a + self.b

class DerivedClass(BaseClass):

    def __init__(self, a, b):
        #Reusing
        super(DerivedClass, self).__init__(a, b)

        #Superclass methods can also be used here
        print self.sum()

if __name__ == '__main__':

    cls = DerivedClass(10, 5)
    print "sum:" + str(cls.sum())
    print "a:" + str(cls.a)
    print "b:" + str(cls.b)

classTest.Output result of py


15
sum:15
a:10
b:5

Description

In init () of DeruvedClass (subclass)

super(DerivedClass, self).__init__(a, b)

Describe as. If you don't want to reuse it, you'll have to write the same code again in Derived Class. So I'm using super () to get the superclass and reuse the constructor.

Also,

print self.sum()

You can use it immediately (that's right)

Recommended Posts

Python: [Inheritance] Reuse superclass constructors in subclasses
Python #inheritance (inheritance)
Quadtree in Python --2
Python in optimization
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
DCI in Python
quicksort in python
nCr in python
N-Gram in Python
About python inheritance
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
Class inheritance practice in python as seen in sklearn
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
Basic story of inheritance in Python (for beginners)
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 18 in Python
Singleton pattern in Python
File operations in Python
Key input in Python
Daily AtCoder # 33 in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python