2011-06-24 125 views
5

考虑一个模块,例如模块。各种模块在相同的解释器过程中使用。这个模块只有一个上下文。为了使some_module方法起作用,它必须接收一个类实例的依赖注入。对模块的依赖注入

什么是pythonic和优雅的方式注入依赖项的模块?

回答

1

恕我直言,认为羽翼丰满Dependency Injection与所有的行话是更适合于静态类型,如Java语言,在Python中,你能够做到这很容易例如,这里是裸骨injection

class DefaultLogger(object): 
    def log(self, line): 
     print line 

_features = { 
    'logger': DefaultLogger 
    } 

def set_feature(name, feature): 
    _features[name] = feature 

def get_feature(name): 
    return _features[name]() 

class Whatever(object): 

    def dosomething(self): 
     feature = get_feature('logger') 

     for i in range(5): 
     feature.log("task %s"%i) 

if __name__ == "__main__": 
    class MyLogger(object): 
     def log(sef, line): 
     print "Cool",line 

    set_feature('logger', MyLogger) 

    Whatever().dosomething() 

输出:

Cool task 0 
Cool task 1 
Cool task 2 
Cool task 3 
Cool task 4 

如果你认为缺少某些东西,我们可以很容易地添加它的python。

+1

这不是依赖注入,而是服务定位器。 – deamon

+0

@deamon可能是没有,可能是'get_feature('logger')'是服务定位器,但set_feature在应用程序开始时注入MyLogger,这是差异之间的良好链接http://martinfowler.com/ articles/injection.html#ServiceLocatorVsDependencyInjection –

+0

不幸的是,这是一个服务定位器。和[服务定位器是一个反模式](http://blog.ploeh.dk/2010/02/03/ServiceLocatorisanAnti-Pattern) –

2

使用模块全局。

import some_module 
some_module.classinstance = MyClass() 

some_module可以有代码来设置一个默认实例,如果没有收到一个,或只设置classinstanceNone和检查,以确保它被调用的方法时设置。