问题
As I understand it, a client (the core program) needs to have a common type to allow a plugin, another object, etc. to be passed successfully to a client. I saw this answer on SO here,
What is dependency injection?
In Java, passing by constructor using an prescript Interface makes sense. From the SO question mentioned,
public SomeClass (MyClass myObject) {
this.myObject = myObject;
}
As I understand it, MyClass is a type defined by an Interface. myObject implements that, is required to in fact, thus allowing me to pass myObject to the constructor.
So how does Dependency Injection work in duck typing language? Python has no Interfaces. Is Python's DI implementation the same as Java or other statically typed languages, or a "workaround" type DI for scripting languages?
回答1:
The need for an interface is just a detail of Java. It's the thing that lets you define a function that can accept an instance of any of several otherwise-unrelated types.
Since every Python function can accept an instance of any type, there is no need for anything comparable.
Of course, if you pass in an object that doesn't have the required capability then you'll get an exception at some point. Python has what is called "implicit interfaces" -- the interface required by the function is whatever operations it performs on the object in the expectation of them working.
来源:https://stackoverflow.com/questions/22695029/how-does-python-implement-dependency-injection-since-it-has-no-interfaces