How to implement interfaces in python?

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

How to implement the 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 that a good idea? Give examples of your answers.

+46
python oop
Jan 23 '10 at 18:29
source share
5 answers

As mentioned here:

Interfaces are not needed in Python. This is because Python has the correct multiple inheritance as well as ducktyping, which means that the places where you should have interfaces in Java, you don't need to have them in Python.

However, there are still several uses for interfaces. Some of them are covered by the Pythons base classes introduced in Python 2.6. They are useful if you want to create base classes that cannot be created, but provide a specific interface or part of an implementation.

Another use is if you somehow want to indicate that an object implements a specific interface, and you can use ABC to do this also by subclassing them. Another way is zope.interface, a module that is part of the Zope component architecture, a really awesome component structure. Here you are not subclasses from interfaces, but instead mark classes (or even instances) as an implementation of the interface. It can also be used to search for components from the component registry. Supercool!

+56
Jan 23 '10 at 19:35
source share

Using the abc module for abstract base classes seems to do the trick.

 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() 
+19
Apr 17 '14 at 13:11
source share

There are third-party implementations of interfaces for Python (the most popular is Zope's , also used in Twisted ), but most often Python coders prefer to use a richer concept known as "Abstract Base Class" (ABC), which combines an interface with the ability to have some aspects implementations there too. ABCs are especially well supported in Python 2.6 and later, see PEP , but even in earlier versions of Python they are usually considered a β€œway to go” - just define a class some of which raises NotImplementedError , so subclasses will be notified that they better override these methods! -)

+18
Jan 23 '10 at 18:33
source share

Something like this (may not work since I don't have Python):

 class IInterface: def show(self): raise NotImplementedError class MyClass(IInterface): def show(self): print "Hello World!" 
+11
Jan 23
source share

I understand that interfaces are not needed in dynamic languages ​​like Python. In Java (or C ++ with an abstract base class), interfaces are a means to ensure that, for example, you pass the correct parameter that is capable of performing a set of tasks.

eg. if you have an observer and an observable, an observable is interested in subscribing to objects that support the IObserver interface, which in turn has a notify action. This is checked at compile time.

There is no such thing as compile time in Python, and method searches are performed at runtime. Moreover, you can override the search using the __getattr __ () or __getattribute __ () methods. In other words, you can pass as an observer any object that can be returned when accessing the notify attribute.

This leads me to the conclusion that interfaces exist in Python - it's just that their enforcement is delayed until they are actually used.

+5
Jan 23 '10 at 7:19
source share



All Articles