我如何在Python中实现接口?

public interface IInterface { void show(); } public class MyClass : IInterface { #region IInterface Members public void show() { Console.WriteLine("Hello World!"); } #endregion } 

我如何实现这个C#代码的Python等价物?

 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!' 

这是一个好主意吗?? 请在答案中给出例子。

正如其他在这里提到的:

Python中不需要接口。 这是因为Python具有适当的多重inheritance,也是ducktyping,这意味着你必须在Java中有接口的地方,你不必使用Python。

也就是说,接口还有几个用途。 它们中的一些被Python 2.6中引入的Pythons抽象基类所涵盖。 如果您想要创build无法实例化的基类,但是提供特定的接口或实现的一部分,则它们非常有用。

另一个用法是,如果你想以某种方式指定一个对象实现一个特定的接口,你也可以通过从它们的子类来使用ABC。 另一种方式是zope.interface,它是Zope Component Architecture的一部分,是一个非常酷的组件框架。 在这里你不要从接口inheritance,而是把类(或者甚至是实例)标记为实现一个接口。 这也可以用来从组件registry中查找组件。 超酷!

使用抽象基类的abc模块似乎可以做到这一点。

 from abc import ABCMeta, abstractmethod class IInterface: __metaclass__ = ABCMeta @classmethod def version(self): return "1.0" @abstractmethod def show(self): raise NotImplementedError class MyServer(IInterface): def show(self): print 'Hello, World 2!' class MyBadServer(object): def show(self): print 'Damn you, world!' class MyClient(object): def __init__(self, server): if not isinstance(server, IInterface): raise Exception('Bad interface') if not IInterface.version() == '1.0': raise Exception('Bad revision') self._server = server def client_show(self): self._server.show() # This call will fail with an exception try: x = MyClient(MyBadServer) except Exception as exc: print 'Failed as it should!' # This will pass with glory MyClient(MyServer()).client_show() 

Python的接口有第三方接口(最受欢迎的是Zope的 ,也用在Twisted中 ),但是更常见的Python编码器更喜欢使用被称为“抽象基类”(ABC)的更丰富的概念,它将接口与那里也有一些实施方面的可能性。 在Python 2.6和更高版本中,ABCs得到了很好的支持,请参阅PEP ,但是即使在Python的早期版本中,它们通常被看作是“要走的路” – 只需定义一个类,其中一些方法引发NotImplementedError以便子类注意他们最好重写这些方法!)

像这样的东西(可能不工作,因为我周围没有Python):

 class IInterface: def show(self): raise NotImplementedError class MyClass(IInterface): def show(self): print "Hello World!" 

我的理解是接口在Python等dynamic语言中不是必需的。 在Java(或C ++及其抽象基类)中,接口是确保你传递正确参数,执行一组任务的方法。

例如,如果您有观察者并且可观察,那么observable就会对支持IObserver接口的订阅对象感兴趣,而接口又会notify操作。 这是在编译时检查的。

在Python中,不存在compile time和方法查找在运行时执行的事情。 而且,可以使用__getattr __()或__getattribute __()魔术方法来覆盖查找。 换句话说,您可以传递任何可以返回可通过访问notify属性的对象作为观察者。

这导致我得出这样的结论:Python中的接口确实存在 – 只是它们的执行被推迟到实际使用它们的时刻