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

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

问题描述

public interface IInterface
{
    void show();
}

 public class MyClass : IInterface
{

    #region IInterface Members

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

    #endregion
}



如何?我实现的Python相当于此C#代码

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 is 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引入了覆盖。如果你想使那些不能被实例化基类,但提供了一个实现的特定接口或部分是非常有用的。

That said, there is still several uses of interfaces. Some of them are covered by Pythons Abstract Base Classes, introduced in Python 2.6. That's useful if you want to make baseclasses that can not 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天全站免登陆