DIコンテナをPythonで書いたんだけど、そもそもPythonで必要あるのか不安になった。

/

- DI/
  - DIContainer.py
 `- __init__.py

`- sample.py

DICOntainer.py

# -*- coding: utf-8 -*-

class DIContainer:
    def __init__(self, c):
        self.objects = dict()
        self.componentFactory = c
        c.accept(self)

    def get(self, name):
        name = name.title()
        if not name in self.objects:
            self.objects[name] = self.componentFactory.get(name)
        return self.objects[name]


class ComponentFactory:
    def __init__(self):
        self.container = None

    def get(self, name):
        method_name = 'build' + name
        return getattr(self, method_name)()

    def accept(self, c):
        self.container = c

__init__.py

# -*- coding: utf-8 -*-
from DIContainer import ComponentFactory
from DIContainer import DIContainer

sample.py

# -*- coding: utf-8 -*-
from DI import ComponentFactory
from DI import DIContainer

class MyComponentFactory(ComponentFactory):
    def __init__(self):
        pass

    def buildDict(self):
        d = dict()
        return d

    def buildList(self):
        l = list()
        return l


if __name__ == '__main__':
    container = DIContainer(MyComponentFactory())

    # オブジェクトをコンテナから取り出す
    d = container.get('dict')
    print(d)

    l = container.get('list')
    print(l)

勉強になった記事。