What is a Pythonic way for Dependency Injection?

后端 未结 9 2116
终归单人心
终归单人心 2020-12-02 06:57

Introduction

For Java, Dependency Injection works as pure OOP, i.e. you provide an interface to be implemented and in your framework code accept an instance of a c

9条回答
  •  粉色の甜心
    2020-12-02 07:49

    There is also Pinject, an open source python dependency injector by Google.

    Here is an example

    >>> class OuterClass(object):
    ...     def __init__(self, inner_class):
    ...         self.inner_class = inner_class
    ...
    >>> class InnerClass(object):
    ...     def __init__(self):
    ...         self.forty_two = 42
    ...
    >>> obj_graph = pinject.new_object_graph()
    >>> outer_class = obj_graph.provide(OuterClass)
    >>> print outer_class.inner_class.forty_two
    42
    

    And here is the source code

提交回复
热议问题