[PYTHON] Inject dependencies into module

In the case of python, you can easily reverse the dependency if it is good for each module. person.py does not depend on the implementation of ʻAbstractPerson`.

person.py


class AbstractPerson:
    def say(self):
        raise NotImplementedError()


def talk_each():
    person_a = AbstractPerson()
    person_b = AbstractPerson()

    print(person_a.say())
    print(person_b.say())

To inject a dependency into the person module, you can write:

main.py


import person


class JapanesePerson:
    def say(self):
        return "Hello"


class EnglishPerson:
    def say(self):
        return "Hi"


person.AbstractPerson = JapanesePerson
person.talk_each()
#Hello
#Hello
person.AbstractPerson = EnglishPerson
person.talk_each()
# Hi
# Hi

It really feels like python.

Recommended Posts

Inject dependencies into module