我如何在python中实现接口? [英] How do I implement interfaces in python?

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

问题描述

public interface IInterface
{
    void show();
}

 public class MyClass : IInterface
{

    #region IInterface Members

    public void show()
    {
        Console.WriteLine("Hello World!");
    }

    #endregion
}

如何实现与此 C# 代码等效的 Python 代码?

How do I implement Python equivalent of this C# code ?

class IInterface(object):
    def __init__(self):
        pass

    def show(self):
        raise Exception("NotImplementedException")


class MyClass(IInterface):
   def __init__(self):
       IInterface.__init__(self)

   def show(self):
       print 'Hello World!'

这是个好主意吗??请在回答中举例说明.

Is this a good idea?? Please give examples in your answers.

推荐答案

正如这里其他人提到的:

As mentioned by other here:

接口在 Python 中不是必需的.这是因为 Python 有适当的多重继承,还有鸭子类型,这意味着你必须在 Java 中有接口的地方,你不必在 Python 中有它们.

Interfaces are not necessary in Python. This is because Python has proper multiple inheritance, and also ducktyping, which means that the places where you must have interfaces in Java, you don't have to have them in Python.

也就是说,接口仍有多种用途.其中一些包含在 Python 2.6 中引入的 Python 抽象基类中.如果您想创建无法实例化但提供特定接口或部分实现的基类,它们很有用.

That said, there are still several uses for interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. They are useful, if you want to make base classes that cannot be instantiated, but provide a specific interface or part of an implementation.

另一种用法是,如果您想以某种方式指定一个对象实现特定接口,您也可以通过从它们子类化来使用 ABC.另一种方法是 zope.interface,一个模块是 Zope 组件架构的一部分,一个非常酷的组件框架.在这里,您不是从接口子类化,而是将类(甚至实例)标记为实现接口.这也可用于从组件注册表中查找组件.超酷!

Another usage is if you somehow want to specify that an object implements a specific interface, and you can use ABC's for that too by subclassing from them. Another way is zope.interface, a module that is a part of the Zope Component Architecture, a really awesomely cool component framework. Here you don't subclass from the interfaces, but instead mark classes (or even instances) as implementing an interface. This can also be used to look up components from a component registry. Supercool!

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

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