I wrote a program quickly to study DI with Python ①

background

The company talked about DI (Dependency Injection), I didn't know Imaichi-chan, so I decided to study

What is DI in the first place?

・ Dependency injection (literal translation) ・ Promotion of componentization by reducing the degree of coupling ・ Efficiency of unit tests · Reduced reliance on specific frameworks ・ There seems to be a DI container (hey)

Personally, I was attracted to the fact that unit testing became easier.

Later, even if it was (apparently) componentized at the time of implementation There is not much merit if they depend on each other.

(The image that you can't do it with Sujiko and how much you have to do is really useless)

I will write it immediately

Anyway, I'll write it.

First, an example of being dependent.

no_di.py


class Country:
    def getCountry(self):
        return "Japanese"


class Position:
    def getPosition(self):
        return 'SuperStar'


class HorseName:
    def getName(self):
        return 'Caesario'


class GreatRealCondition:
    def __init__(self):
        self.c = Country()
        self.p = Position()
        self.h = HorseName()

    def getGreatRealCondition(self):
        return self.c.getCountry() + "\n" + self.p.getPosition() + "\n" + self.h.getName() + "!"


if __name__ == '__main__':
    g = GreatRealCondition()
    print(g.getGreatRealCondition())

Execution result.


Japanese
SuperStar
Caesario!

If you don't know what the text is, youtube Search for "Japanese Superstar Cesario!"

The GreatRealCondition class

・ Country class ・ Position class ・ HorseName class

It has a close relationship with these classes (** Three Cs **).

So it can be said that these classes look disjointed and are actually almost one class.

It can't be reused, and it can't be tested in the first place (you can't change the value or anything at the moment). You can change the value by putting a setter in the Country class etc., but it is no longer a test of the GreatRealCondition class.

So, try lowering the dependency.

on_di.py


class Country:
    def getCountry(self):
        return "Japanese"


class Position:
    def getPosition(self):
        return 'SuperStar'


class HorseName:
    def getName(self):
        return 'Caesario'


class GreatRealCondition:
    def __init__(self, c: Country, p: Position, h: HorseName):
        self.c = c
        self.p = p
        self.h = h

    def getGreatRealCondition(self):
        return self.c.getCountry() + "\n" + self.p.getPosition() + "\n" + self.h.getName() + "!"


if __name__ == '__main__':
    c = Country()
    p = Position()
    h = HorseName()
    g = GreatRealCondition(c, p, h)
    print(g.getGreatRealCondition())

Execution result.


Japanese
SuperStar
Caesario!

The result was the same as before.

The big change here is

** GreatRealCondition class no longer has other classes **

Exhausted.

The GreatRealCondition class, which relied on the three-cs class and had no other use,

By having 3 dense classes in the constructor, various uses were possible. (Actually, I thought I'd try various patterns, but it's going to be long, so this time)

Well, I used the constructor to "inject dependencies".

At first it looks like this.

from now on

This time I injected using the constructor,

It seems that there are various methods such as injection with setter and injection by defining the interface, so I will definitely try it.

Also, python may be quite DI troublesome. (I'm just not used to it)

Thanks!!

Here is a helpful article. Thank you very much. https://qiita.com/mkgask/items/d984f7f4d94cc39d8e3c

Recommended Posts

I wrote a program quickly to study DI with Python ①
I wrote a script to create a Twitter Bot development environment quickly with AWS Lambda + Python 2.7
I want to make a game with Python
I want to write to a file with Python
I tried to create a program to convert hexadecimal numbers to decimal numbers with python
I want to generate a UUID quickly (memorandum) ~ Python ~
I tried to draw a route map with Python
I want to work with a robot in python.
From buying a computer to running a program with python
I tried to automatically generate a password with Python3
A program to write Lattice Hinge with Rhinoceros with Python
[Python, ObsPy] I wrote a beach ball with Matplotlib + ObsPy
I want to run a quantum computer with Python
I made a package to filter time series with python
I made a program to convert images into ASCII art with Python and OpenCV
I made a fortune with Python.
I want to debug with Python
I made a daemon with Python
I made a program to collect images in tweets that I liked on twitter with Python
I wrote a doctest in "I tried to simulate the probability of a bingo game with Python"
How to batch start a python program created with Jupyter notebook
I made a library to easily read config files with Python
[3rd] I tried to make a certain authenticator-like tool with python
[Python] A memo that I tried to get started with asyncio
I wrote a script to get you started with AtCoder fast!
I tried to create a list of prime numbers with python
I want to do a full text search with elasticsearch + python
I wrote a function to load a Git extension script in Python
I tried to make a periodical process with Selenium and Python
I tried to make a 2channel post notification application with Python
I wanted to solve the ABC164 A ~ D problem with Python
[Introduction] I want to make a Mastodon Bot with Python! 【Beginners】
I wrote a script to extract a web page link in Python
I tried to create Bulls and Cows with a shell program
I tried to make a todo application using bottle with python
[4th] I tried to make a certain authenticator-like tool with python
[1st] I tried to make a certain authenticator-like tool with python
[Python] A program that creates stairs with #
I made a payroll program in Python!
I made a character counter with Python
I installed Python 3.5.1 to study machine learning
I drew a heatmap with seaborn [Python]
I wanted to solve ABC160 with Python
I want to build a Python environment
I want to analyze logs with Python
I want to play with aws with python
I tried a functional language with Python
What I did with a Python array
I made a Hex map with Python
I made a roguelike game with Python
I wanted to solve ABC172 with Python
I made a simple blackjack with Python
I made a configuration file with Python
I made a neuron simulator with Python
What skills do I need to program with the FBX SDK Python?
Python: I tried to make a flat / flat_map just right with a generator
I tried to communicate with a remote server by Socket communication with Python.
I made a tool to automatically browse multiple sites with Selenium (Python)
I was addicted to creating a Python venv environment with VS Code
I tried to make a traffic light-like with Raspberry Pi 4 (Python edition)
I get a UnicodeDecodeError when trying to connect to oracle with python sqlalchemy