LoginSignup
0
0

More than 3 years have passed since last update.

module に依存性を注入する

Last updated at Posted at 2020-10-17

python の場合、module ごとでよければ、簡単に依存性を逆転できる。
person.pyAbstractPerson の実装に依存しない。

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())

person module に依存性を注入する場合は、以下のように書ける。

main.py
import person


class JapanesePerson:
    def say(self):
        return "こんにちは"


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


person.AbstractPerson = JapanesePerson
person.talk_each()
# こんにちは
# こんにちは
person.AbstractPerson = EnglishPerson
person.talk_each()
# Hi
# Hi

いかにも python という感じがする。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0