[PYTHON] Comparison of class inheritance and constructor description

Introduction

It all started when I tried to inherit classes in Python. From the perspective of myself, who has been dealing with Java so far, I thought, "What's this !!!!!!", so in some programming languages I compared the description method of class inheritance with the description method & behavior of the constructor.

This stance

Write, compare, view, and express your impressions around Java.

I used paiza.IO to check the operation. Convenient. https://paiza.io/ja

Sample specifications

--Parent class (Super class) --A default constructor is available. Output the character string of "★ Parent constructor" to the console --Prepare one function / method --Output the character string passed as an argument to the console --Child class (inheriting class) --Inherit the Parent class --A default constructor is available. Output the character string of "☆ Child constructor" to the console --Prepare one function / method --Output the character string passed as an argument to the console --Call the function / method of Super class with the character string "★ Parent function / method can be called" as an argument. --Main class / main script (execution source) --In paiza.IO, the name of the Java execution source (including the main method) class must be Main, and this name --Instantiate the Child class -Call the child class function / method with the character string "☆ Child function / method can be called" as an argument.

Java Personally, it's the most familiar language. The version is Java 12.

Class inheritance description method

Constructor description method

sample

Parent.java


public class Parent {
    
    public Parent(){
        System.out.println("★ Parent constructor");
    }
    
    protected void parentMethod(String message){        
        System.out.println(message);
    }
}

Child.java


public class Child extends Parent{

    public Child(){
        System.out.println("☆ Child constructor");
    }

    public void childMethod(String message){       
        System.out.println(message);
        parentMethod("★ You can call the Parent method");
    }
}

Main.java


public class Main {
    public static void main(String[] args) {

        Child child = new Child();
        child.childMethod("☆ You can call the Child method");
    }
}

Execution result (console)

★ Parent constructor ☆ Child constructor ☆ You can call the Child method ★ You can call the Parent method

Impressions

--How to write class inheritance and constructor that suits you best personally --The default constructor of the parent class is also implicitly called --Multiple constructors with different arguments can be implemented

Python Next, the opportunity to write this article. The version is Python 3.6.8.

Class inheritance description method

** class ** * Inheriting class * ** (** * Super class * **): **

Constructor description method

** def \ _ \ _ init \ _ \ _ (self ** *, if any argument * **): ** ** Initial value setting process for instance self **

** def \ _ \ _ new \ _ \ _ (cls ** *, if any argument * **): ** ** return super (). \ _ \ _ New \ _ \ _ (cls ** *, if any argument * **) **

** * The following samples, execution results (console), and impressions are about the \ _ \ _ init \ _ \ _ function. ** **

sample

parent.py


class Parent(object):

    def __init__(self):
        print('★ Parent constructor')

    def parent_function(self, message):
        print(message)

child.py


from parent import Parent

class Child(Parent):

    def __init__(self):
        print('☆ Child constructor')

    def child_function(self, message):
        print(message)
        Parent.parent_function(self, '★ You can call the Parent function')

main.py


from child import Child

def main():
    ch = Child()
    ch.child_function('☆ You can call the child function')
    

if __name__ == '__main__':
    main()

Execution result (console)

☆ Child constructor ☆ You can call the child function ★ You can call the Parent function

Impressions

―― "Well, do you use parentheses in class inheritance? Isn't it wrong with the argument?" --Because Python treats everything as an object? --The \ _ \ _ init \ _ \ _ function of the Parent class is overwritten by the \ _ \ _ init \ _ \ _ function of the Child class. --When the \ _ \ _ init \ _ \ _ function of the Child class is deleted and executed, "★ Parent constructor" is output. --If you also want to execute the \ _ \ _ init \ _ \ _ function of the Parent class, it seems that you need to make it explicit as follows.

child.py


from parent import Parent

class Child(Parent):

    def __init__(self):
        Parent.__init__(self) #Added here! !! !! !! !! !!
        print('☆ Child constructor')

    def child_function(self, message):
        print(message)
        Parent.parent_function(self, '★ You can call the Parent function')

-Only one \ _ \ _ init \ _ \ _ function can be prepared in one class --Can't be Java-like --If you want multiple constructors, it seems better to use the default arguments - https://qiita.com/miyashiiii/items/9dcb2114ac0843a73fce

\ _ \ _ New \ _ \ _ Function * (2019/8/16) Added

Initially, I only mentioned the \ _ \ _ init () \ _ \ _ function, Since I received comments, I also investigated the \ _ \ _ new \ _ \ _ function.

-** \ _ \ _ new \ _ \ _ function works ** when instantiating, so it works before ** \ _ \ _ init \ _ \ _ function . - \ _ \ _ init \ _ \ _ function works ** after the instance is created

Below is from the Python 3.7.4 documentation.

When implementing the \ _ \ _ new \ _ \ _ function, you need return super () .__ new __ (cls [, ...]). https://docs.python.org/ja/3/reference/datamodel.html#object.new

In a typical implementation, when creating a new instance of a class, specify the appropriate arguments for super (). \ _ \ _ New \ _ \ _ (cls [, ...]) and \ _ for the super class. Call the \ _new \ _ \ _ () method to make the necessary changes to the newly created instance before returning it.

It was written properly (´ ・ ω ・ `) https://docs.python.org/ja/3/reference/datamodel.html#object.init

Called after the instance is created (by \ _ \ _ new \ _ \ _ ()) and before it is returned to the caller. The arguments are what you pass to the class's constructor expression. If both the base class and its derived class have \ _ \ _ init \ _ \ _ () methods, then the derived class's \ _ \ _ init \ _ \ _ () method is the base class's \ _ \ _ init \ _ \ _ ( ) You must explicitly call the method to ensure that the base class part of the instance is properly initialized. For example, super (). \ _ \ _ Init \ _ \ _ ([args ...]).

It seems that the \ _ \ _ new \ _ \ _ function was better if it was lined up with the Java constructor. ..

When I replaced the sample implemented by the \ _ \ _ init \ _ \ _ function with the \ _ \ _ new \ _ \ _ function as it is, The execution result (console) is as follows. ☆ Child constructor ★ Parent constructor ☆ You can call the child function ★ You can call the Parent function

Ruby By the mysterious logic that Python and Ruby. The version is Ruby 2.6.3.

Class inheritance description method

** class ** * Inheriting class * ** <** * Super class * end

Constructor description method

** def initialize (** * if any argument * **) ** end

sample

parent.rb


class Parent

    def initialize()
        puts "★ Parent constructor"
    end
    
    def parent_function(message)
        puts message
    end   
end

child.rb


require("./parent.rb")

class Child < Parent

    def initialize()
        puts "☆ Child constructor"
    end
    
    def child_function(message)
        puts message
        parent_function("★ You can call the Parent function")
    end
end

main.rb


require("./child.rb")

child = Child.new
child.child_function("☆ You can call the child function")

Execution result (console)

☆ Child constructor ☆ You can call the child function ★ You can call the Parent function

Impressions

――It seems like a description that conveys the feeling of inheritance of the class. It's Python-like that the constructor is a function with a fixed name --Similar to Python, the initialize function of the Parent class is overwritten by the initialize function of the Child class. --When the initialize function of Child class is deleted and executed, "★ Parent constructor" is output. --With super, also execute Parent's initialize function

child.rb


require("./parent.rb")

class Child < Parent

    def initialize()
        super()  #Added here! !! !! !! !! !!
        puts "☆ Child constructor"
    end
    
    def child_function(message)
        puts message
        parent_function("★ You can call the Parent function")
    end
end

--Only one initialize function can be prepared for each class --This is also similar to Python --Similarly, if you want multiple constructors, it seems better to use the default arguments. - https://blog.goo.ne.jp/korokoro-2/e/d62a1c524beecfe3dd6a8ce8c9dab257

PowerShell In the training for new employees at the company, there was a theme to create a PowerShell script, so I included it. There was no class inheritance in PowerShell (Kiri), so I was thinking of making it a punch line ... **. ** ** This was not on paiza.IO, so I checked the operation on my PC.

Class inheritance description method

** class ** * Inheriting class * : ** * Super class * ** { }

Constructor description method

sample

parent.psm1


class Parent {

    Parent() {
        write-host("★ Parent constructor")
    }

    parent_function([String] $message) {

        write-host($message)
    }
}

child.ps1


using module ".\parent.psm1"

class Child : Parent {

    Child(){
         write-host("☆ Child constructor")       
    }

    child_function([String] $message) {

        write-host($message)
        ([Parent]$this).parent_function("★ You can call the Parent function")
    }
}

main.ps1


. .\child.ps1

$child = [Child]::new()
$child.child_function("☆ You can call the child function")

Execution result (console)

★ Parent constructor ☆ Child constructor ☆ You can call the child function ★ You can call the Parent function

Impressions

--For class inheritance, "colon?" The constructor is Java-like --Like Java, the constructor of the Parent class is also implicitly called --Similar to Java, multiple constructors with different arguments can be implemented. ――I tried to end it with "Well, it's Java-like", but ** it doesn't work ** -** Class inheritance across files is not straightforward ** --The Super class file should be a module file (extension is **. Psm1 ) and called with ʻusing module. ――I have to change the extension ... why? ?? ?? -** Super class functions can only be called by "casting the inheriting class $ this` with the Super class " --Cast this ... why? ?? ??

at the end

Other than Java, Python, Ruby, and PowerShell were "I've written but never used classes" choices. I thought I'd try a couple of other programming languages that I hadn't touched before. I'm sorry, I'm exhausted with PowerShell.

paiza.IO has many programming languages that can be used, so If I feel better, I would like to add it if I try other things. ** Anyway, paiza.IO is really convenient. ** **

Compare how to write It was fun to understand the characteristics of each programming language and the looseness of my understanding! Thank you for staying with us until the end.

Recommended Posts

Comparison of class inheritance and constructor description
Class inheritance and super functions
Comparison of Apex and Lamvery
[Python of Hikari-] Chapter 09-03 Class (inheritance)
Calculation of homebrew class and existing class
Class inheritance
Example of using class variables and class methods
Comparison of gem, bundler and pip, venv
Comparison of L1 regularization and Leaky Relu
Speed comparison of murmurhash3, md5 and sha1
Comparison of k-means implementation examples of scikit-learn and pyclustering
Constructor and destructor
Comparison of R and Python writing (Euclidean algorithm)
General description of the CPUFreq core and CPUFreq notifiers
[Python] Class type and usage of datetime module
Summary of pickle and unpickle processing of user-defined class
Comparison of Python and Ruby (Environment / Grammar / Literal)
A quick comparison of Python and node.js test libraries
DNN (Deep Learning) Library: Comparison of chainer and TensorFlow (1)
Comparison of Windows Server and Free Linux to Commercial Linux
Comparison table of frequently used processes of Python and Clojure
Sample of getting module name and class name in Python
Overview of class-based generic views and inherited class relationships
Comparison of CoffeeScript with JavaScript, Python and Ruby grammar
About Class and Instance
Multiple inheritance of classes
[Python] Class inheritance (super)
Comparison of LDA implementations
Comparison of online classifiers
[Python] Class inheritance, override
Comparison of fitting programs
Class methods and static methods
Comparison of how to use higher-order functions in Python 2 and 3
Comparison of Hungarian law and general-purpose solver for allocation problems