Python没有接口,如何实现依赖注入? [英] How does Python implement Dependency Injection since it has no Interfaces?

查看:109
本文介绍了Python没有接口,如何实现依赖注入?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我了解,客户端(核心程序)需要具有通用类型,以允许插件,另一个对象等成功传递给客户端。我在这里看到了这样的答案,

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,

什么是依赖注入?

在Java中,使用规定的接口传递构造函数很有意义。从提到的SO问题开始,

In Java, passing by constructor using an prescript Interface makes sense. From the SO question mentioned,

public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}

据我了解,MyClass是由接口定义的类型。 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.

那么依赖注入在鸭子类型语言中如何工作? Python没有接口。 Python的DI实现与Java或其他静态类型的语言相同,还是脚本语言的替代类型DI?

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?

推荐答案

接口的需要只是Java的一个细节。正是这个东西让您定义了一个可以接受其他几种不相关类型的实例的函数。

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.

由于每个Python函数都可以接受任何类型的实例,

Since every Python function can accept an instance of any type, there is no need for anything comparable.

当然,如果传入的对象没有所需的功能,则有时会出现异常。 Python具有所谓的隐式接口(implicit interfaces),该函数所需要的接口就是它在对象上执行的,期望它们起作用的任何操作。

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.

这篇关于Python没有接口,如何实现依赖注入?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆