[Python] Class inheritance (super)

Class inheritance

As the name suggests, create a derived class that has the function of a base class.

Inheritance of one class

Here, the Warrior and Magician classes are simply created based on the Creature class. The ability is increased according to the initial level.

The status (self) function enumerates the parameters. (for test) __init__ is executed at the time of instantiation. In the Worrior and Magician classes, we have weapons and change occupation names.

clas_test1.py


class Creature(object):
    def __init__(self, level=1, weapon=None):
        self.level = level
        self.hp = 0
        self.mp = 0
        self.attack = 0
        self.defence = 0
        self.weapon = weapon
        self.job = "neet"

    def status(self):
        return "Job:{} | HP:{} | MP:{} | Atk:{} | Def:{} | Weapon:{}".format \
                (self.job, self.hp, self.mp, self.attack, self.defence, self.weapon)


class Warrior(Creature):
    def __init__(self, level):
        super().__init__(level)
        self.attack += 3 * level
        if self.weapon is None:
            self.weapon = "sword"
        if self.job == "neet":
            self.job = "Warrior"
        else: self.job += "Warrior"


class Magician(Creature):
    def __init__(self, level):
        super().__init__(level)
        self.mp += 4 * level
        if self.weapon is None:
            self.weapon = "rod"
        if self.job == "neet":
            self.job = "Magic"
        else: self.job += "Magic"

As shown below, the ability increases according to the level, and the status function of the base class can be used.

test1.py


>>> print(Warrior(5).status())
Job:Warrior | HP:0 | MP:0 | Atk:15 | Def:0 | Weapon:sword
>>> print(Magician(5).status())
Job:Magic | HP:0 | MP:20 | Atk:0 | Def:0 | Weapon:rod

Multiple class inheritance

In the case of multiple classes, the same thing as before is almost the same.

class_test2.py


class MagicWarrior(Warrior, Magician):
    def __init__(self, level):
        super().__init__(level)


class WarriorMagic(Magician, Warrior):
    def __init__(self, level):
        super().__init__(level)

Here, the point to note is, as you can see in the output below. When super () is used, the order in which __init__ is called is from the back. This order can be confirmed with mro ().

test2.py


>>> print(MagicWarrior(5).status())
Job:MagicWarrior | HP:0 | MP:20 | Atk:15 | Def:0 | Weapon:rod
>>> print(WarriorMagic(5).status())
Job:WarriorMagic | HP:0 | MP:20 | Atk:15 | Def:0 | Weapon:sword
>>>
>>> WarriorMagic.mro()
[<class 'class_test.WarriorMagic'>, <class 'class_test.Magician'>, <class 'class_test.Warrior'>, <class 'class_test.Creature'>, <class 'object'>]

What happens if you don't use super

For example

class_test3.py


class WarriorMagic(Magician, Warrior):
    def __init__(self, level):
        # super().__init__(level)
        Warrior.__init__(self, level)
        Magician.__init__(self, level)

At first glance, it looks the same, but the number of init calls is different. In this case, Warrior> Creature, Magician> Warrior> Creature I'm calling it like this.

When using super, Magician> Warrior> Creature And the number of calls is different.  Job:WarriorMagic | HP:0 | MP:20 | Atk:15 | Def:0 | Weapon:sword

Furthermore, if the base classes Warrior and Magician classes are also defined without using super

class_test4.py


class Warrior(Creature):
    def __init__(self, level):
        # super().__init__(level)
        Creature.__init__(self, level)
        self.attack += 3 * level
        if self.weapon is None:
            self.weapon = "sword"
        if self.job == "neet":
            self.job = "Warrior"
        else: self.job += "Warrior"


class Magician(Creature):
    def __init__(self, level):
        # super().__init__(level)
        Creature.__init__(self, level)
        self.mp += 4 * level
        if self.weapon is None:
            self.weapon = "rod"
        if self.job == "neet":
            self.job = "Magic"
        else: self.job += "Magic"

test4.py


Job:Magic | HP:0 | MP:20 | Atk:0 | Def:0 | Weapon:rod

By doing this, even though I gained abilities in the first Warrior, Since the second init was called by Magician, the parameters were initialized and only Magician's ability was assigned. As a result, it will be as below.

In the flow, Warrior > Creature, Magician > Creature As you can see, Creature is called twice, and unlike before, Warrior is not called the second time, so Worrior's init is not reflected. I have.

Summary

For the time being, basically use super when inheriting When using super, it is called from behind

Recommended Posts

[Python] Class inheritance (super)
[Python] Class inheritance, override
[python] super (), inheritance, __init__, etc.
Class inheritance
Class inheritance and super functions
Python #inheritance (inheritance)
[Python of Hikari-] Chapter 09-03 Class (inheritance)
[Python] class, instance
"Kanrika" python class
About python, class
About python inheritance
Python class, instance
#Python basics (class)
python syslog wrapper class
Python class (Python learning memo ⑦)
case class in python
Try to solve the Python class inheritance problem
[Python] Super useful debugging
Python self-made class sort
[python] class basic methods
python subprocess wrapper class
Trouble with Python pseudo-private variables and class inheritance
Class inheritance practice in python as seen in sklearn
YOLO Python wrapper class
Class notation in Python
Python exception class list
python memorandum super basic
Python: Class and instance variables
python super beginner tries scraping
C / C ++ programmer challenges Python (class)
Super tiny struct in python
Python class member scope summary
Python class variables and instance variables
Python #function 2 for super beginners
Python for super beginners Python #functions 1
Python #list for super beginners
How to write a Python class
Python
Landmines hidden in Python class variables
Python for super beginners Python # dictionary type 1 for super beginners
Python class definitions and instance handling
"The easiest Python introductory class" modified
I looked into class inheritance overrides.
Read PNG chunks in Python (class)
class
[Python] Road to snake charmer (3) Python class
Python #index for super beginners, slices
Python #len function for super beginners
Examine the object's class in python
perl objects and python class part 1.
[Python] Reasons for overriding using super ()
Python #Hello World for super beginners
class
Python for super beginners Python # dictionary type 2 for super beginners
[Python] Inherit a class with class variables
Understanding python classes Struggle (2) Work That's not all, right? _ About class inheritance
Generate a first class collection in Python
[Python] Extension using inheritance of matplotlib (NavigationToolbar2TK)
Create a Python function decorator with Class
[Python] Super easy test with assert statement
Implement __eq__ etc. generically in Python class