依赖注入框架在动态类型语言中几乎没有那么有用。例如,请参见Java中的表示Dependency Injection: Vitally important or totally irrelevant?依赖注入框架提供的灵活性是至关重要的,而在Python中,这通常会导致不必要的复杂性。
这并不意味着原则是错误的。请参阅以下示例如何使用简单的习惯用法实现类之间的松散耦合:# A concrete class implementing the greeting provider interface
class EnglishGreetingProvider(object):
def get_greeting(self, who):
return "Hello %s!" % who
# A class that takes a greeting provider factory as a parameter
class ConsoleGreeter(object):
def __init__(self, who, provider=EnglishGreetingProvider):
self.who = who
self.provider = provider()
def greet(self):
print(self.provider.get_greeting(self.who))
# Default wiring
greeter = ConsoleGreeter(who="World")
greeter.greet()
# Alternative implementation
class FrenchGreetingProvider(object):
def get_greeting(self, who):
return "Bonjour %s!" % who
greeter = ConsoleGreeter(who="World", provider=FrenchGreetingProvider)
greeter.greet()