[Python] Object-oriented programming learned with Pokemon

Recently, Pokemon Sword Shield has been released and is very popular.

So, taking advantage of this Pokemon popularity, I will explain object-oriented programming using Pokemon.

What is object-oriented programming?

The literal translation of an object is "thing". In other words, we are trying to program like making things.

Things should have features, parts, and behavior. ** The type of thing is called "class", each thing is called "instance", and the behavior of thing is called "method" **.

For example, consider the Pokemon Charizard. Charizard has statuses such as name, level, HP, and attack.

There are various names of Charizard (instances) such as "Rizasuke" and "Rizamaru" in the race (class) called Charizard.

Also, one of the techniques that Charizard learns is flamethrower. This is the method.

The code for these is as follows.

#Charizard class
class Charizard(object):
    #The part that moves when you create an instance(So-called initial setting)
    def __init__(self,name,level,hp,attack,defence,sp_attack,sp_defence,speed):
        self.name = name
    #You can do more than just define values
        print('Go!{}!'.format(self.name))
        self.level = level
        self.type1 = 'Fire'
        self.type2 = 'flight'
        self.hp = hp
        self.attack = attack
        self.defence = defence
        self.sp_attack = sp_attack
        self.sp_defence = sp_defence
        self.speed = speed
        
    #Flamethrower(Method)
    def flame_radiation(self,enemy):
        #Compatibility correction
        compatibility_coefficient = 1
        for Type in [enemy.type1,enemy.type2]:
            if Type == 'Kusa'or'insect'or'Ice'or'Steel':
                compatibility_coefficient *= 2
                
    #Damage calculation(You don't have to know this expression when using the method(Encapsulation))
        damage = ((self.level*2/5+2)*(90*self.sp_attack/enemy.sp_defence)/50+2)*compatibility_coefficient

        print('{}Flamethrower!'.format(self.name))
        print('{}Is{}To{}Damaged!'.format(self.name,enemy.name,np.round(damage)))
        if compatibility_coefficient >= 2:
            print('This one's excellent! !!')

#This is an instance
rizasuke = Charizard('Rizasuke',100,297,183,192,317,206,328)
#This is also an instance
rizamaru = Charizard('Rizamaru',50,200,100,100,150,100,150)

Once the class is loaded, it can be easily executed with just a few lines of code.

By the way, regarding the method, interestingly, it can be executed even if it targets another class.

Let's create a Venusaur class as a trial and execute the flame radiation method on the Venusaur class.

class Fushigibana(object):
    def __init__(self,name,level,hp,attack,defence,sp_attack,sp_defence,speed):
        self.name = name
        print('Go!{}!'.format(self.name))
        self.level = level
        self.type1 = 'Kusa'
        self.type2 = 'Doku'
        self.hp = hp
        self.attack = attack
        self.defence = defence
        self.sp_attack = sp_attack
        self.sp_defence = sp_defence
        self.speed = speed

rizasuke = Charizard('Rizasuke',100,297,183,192,317,206,328)
fussi = Fushigibana('Fusshi',100,364,180,202,328,236,196)
rizasuke.flame_radiation(fussi)

##Execution result
#Go! Rizasuke!
#Go! Fusshi!
#Rizasuke's flamethrower!
#Rizasuke is 414.Inflicted 0 damage!
#This one's excellent! !!

There are three major features of object-oriented programming:

·Encapsulation ** ・ Inheritance ** ** ・ Polymorphism **

Encapsulation (information hiding)

There was a damage calculation formula in the flame radiation method earlier. It's a complicated expression from the appearance.

However, when you actually execute the method, you can easily execute it by writing `rizasuke.flame_radiation (fussi)`. You don't need to know the damage formula.

In a general example, the print () function is the same. It's a function that can be easily output, but only a few people know what it's doing.

This kind of ** hiding information and processing inside the class ** is called encapsulation. Encapsulation prevents internal information from being rewritten and makes it easier to understand classes and methods.

In addition, information such as status is written together in one class, which makes management easier.

Inheritance

Object-oriented programming is very convenient just to summarize the features and behaviors like the code above, but it is now said that there are 890 types of Pokemon (from wikipedia). Writing each method of Pokemon from scratch is tedious.

That's where "inheritance" (override) comes in handy. All you have to do is put the parent class in the argument of the small class and then put the `super (). Method you want to inherit.

Here, Pokemon classes are set to share skills such as HP and attack status and flame radiation.

By implementing a new Pokemon class (parent class) like the code below and inheriting it to child classes such as Charizard and Dragonite, it is not necessary to write the code of status and technique twice. With this, it seems that 890 kinds of Pokemon can be implemented without difficulty.

#Parent class
class Pokemon(object):
    def __init__(self,name,level,hp,attack,defence,sp_attack,sp_defence,speed):
        self.name = name
        print('Go!{}!'.format(self.name))
        self.level = level
        self.type1 = None
        self.type2 = None
        self.hp = hp
        self.attack = attack
        self.defence = defence
        self.sp_attack = sp_attack
        self.sp_defence = sp_defence
        self.speed = speed
        
    #Flamethrower
    def flame_radiation(self,enemy):
        #Compatibility correction
        compatibility_coefficient = 1
        for Type in [enemy.type1,enemy.type2]:
            if Type == 'Kusa'or'insect'or'Ice'or'Steel':
                compatibility_coefficient *= 2
                
        damage = ((self.level*2/5+2)*(90*self.sp_attack/enemy.sp_defence)/50+2)*compatibility_coefficient
        print('{}Flamethrower!'.format(self.name))
        print('{}Is{}To{}Damaged!'.format(self.name,enemy.name,np.round(damage)))
        if compatibility_coefficient >= 2:
            print('This one's excellent! !!')

#Charizard(Child class)
class Charizard(Pokemon):
    def __init__(self,name,level,hp,attack,defence,sp_attack,sp_defence,speed):
        super().__init__(name,level,hp,attack,defence,sp_attack,sp_defence,speed)
        self.type1 = 'Fire'
        self.type2 = 'flight'
        
    def flame_radiation(self,enemy):
        super().flame_radiation(enemy)

#Dragonite(Child class) 
class Cairyu(Pokemon):
    def __init__(self,name,level,hp,attack,defence,sp_attack,sp_defence,speed):
        super().__init__(name,level,hp,attack,defence,sp_attack,sp_defence,speed)
        self.type1 = 'Dragon'
        self.type2 = 'flight'
        
    def flame_radiation(self,enemy):
        super().flame_radiation(enemy)
        #Characteristics only attached to the flame radiation of dragonite(Tentative properties for explaining polymorphism)
        print('The other person got burned!')
        
rizasuke = Charizard('Rizasuke',100,297,183,192,317,206,328)
ryu_kun = Cairyu('Ryu-kun',100,323,403,226,212,299,196)
rizasuke.flame_radiation(ryu_kun)
ryu_kun.flame_radiation(rizasuke)

##Execution result
#Go! Rizasuke!
#Go! Ryu-kun!
#Rizasuke's flamethrower!
#Rizasuke Haryu-kun 329.Inflicted 0 damage!
#Ryu-kun's flamethrower!
#Ryu-kun Harizasuke ni 319.Inflicted 0 damage!
#The other person got burned!

Polymorphism

Polymorphism is literally called polymorphism, polymorphism, and diversity. I think diversity is the most familiar.

A major feature is that when used in combination with inheritance, ** the same command can produce different results (various results) **.

Take a look at the code given in the inheritance example again. In the flamethrower method of Dragonite, in addition to `super (). Flame_radiation (enemy)` `,` `print ('the other party got burned!')` Is included. It is not included in Charizard's flamethrower method.

By doing this, Charizard's flamethrower will not be burned, and Dragonite's flamethrower will always be burned (actual Pokemon is not such a specification).

Summary

"Object-oriented programming learned from Pokemon" itself is a second brew, but there is nothing that explains the three major elements of object-oriented programming such as encapsulation and inheritance. I hope it can be communicated well.

However, it is more familiar than learning, and it will definitely deepen your understanding if you actually write it, and you will gradually understand the merits of object-oriented programming.

If you are a beginner, don't be shy about object-oriented programming, and please try to write it yourself.

References

I don't understand object orientation! Preparatory exercises to turn your brain miso into an object brain [Python] Concept and writing of object-oriented programming

Recommended Posts

[Python] Object-oriented programming learned with Pokemon
3. 3. AI programming with Python
Python programming with Atom
Competitive programming with python
Programming with Python Flask
Programming with Python and Tkinter
Machine learning learned with Pokemon
Network programming with Python Scapy
[Swift / Ruby / Python / Java] Object-oriented programming
Easy Python + OpenCV programming with Canopy
Perceptron learning experiment learned with Python
Python data structures learned with chemoinformatics
Efficient net pick-up learned with Python
1. Statistics learned with Python 1-1. Basic statistics (Pandas)
[Python] Reactive Extensions learned with RxPY (3.0.1) [Rx]
Competitive programming with python Local environment settings
Algorithm learned with Python 10th: Binary search
Algorithm learned with Python 5th: Fibonacci sequence
Algorithm learned with Python 9th: Linear search
Algorithm learned with Python 7th: Year conversion
Algorithm learned with Python 8th: Evaluation of algorithm
Algorithm learned with Python 4th: Prime numbers
Algorithm learned with Python 2nd: Vending machine
Algorithm learned with Python 19th: Sorting (heapsort)
Algorithm learned with Python 6th: Leap year
1. Statistics learned with Python 1-3. Calculation of various statistics (statistics)
Algorithm learned with Python 3rd: Radix conversion
Algorithm learned with Python 12th: Maze search
Algorithm learned with Python 11th: Tree structure
FizzBuzz with Python3
Python programming note
Scraping with Python
Statistics with python
Scraping with Python
Python with Go
Twilio with Python
Integrate with Python
Play with 2016-Python
AES256 with python
Tested with Python
Programming in python
python starts with ()
with syntax (Python)
Bingo with python
Zundokokiyoshi with python
Excel with Python
Microcomputer with Python
Cast with python
I made a competitive programming glossary with Python
How to enjoy programming with Minecraft (Ruby, Python)
What is "functional programming" and "object-oriented" in Python?
Algorithm learned with Python 13th: Tower of Hanoi
Algorithm learned with Python 16th: Sorting (insertion sort)
Optimization learned with OR-Tools [Linear programming: multi-stage model]
Algorithm learned with Python 14th: Tic-tac-toe (ox problem)
Algorithm learned with Python 15th: Sorting (selection sort)
1. Statistics learned with Python 1-2. Calculation of various statistics (Numpy)
Algorithm learned with Python 17th: Sorting (bubble sort)
Use Python and word2vec (learned) with Azure Databricks
1. Statistics learned with Python 2-1. Probability distribution [discrete variable]
Optimization learned with OR-Tools [Linear programming: project management]