tags:

views:

157

answers:

4
public interface IInterface
{
    void show();
}

 public class MyClass : IInterface
{

    #region IInterface Members

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

    #endregion
}

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.

+5  A: 

There are third-party implementations of interfaces for Python (most popular is Zope's, also used in Twisted), but more commonly Python coders prefer to use the richer concept known as an "Abstract Base Class" (ABC), which combines an interface with the possibility of having some implementation aspects there too. ABCs are particularly well supported in Python 2.6 and later, see the PEP, but even in earlier versions of Python they're normally seen as "the way to go" -- just define a class some of whose methods raise NotImplementedError so that subclasses will be on notice that they'd better override those methods!-)

Alex Martelli
*There are third-party implementations of interfaces for Python* What does it mean? Could you please explain ABC ?
TheMachineCharmer
Well, I'll take issue with ABC's being "richer". ;) There are things zope.interface can do that ABC's can't as well as the other way around. But otherwise you are as usual right. +1
Lennart Regebro
@Alfred: It means that modules like zope.interface is not included in the standard library, but available from pypi.
Lennart Regebro
+2  A: 

Something like this (might not work as I don't have Python around):

class IInterface:
    def show(self): raise NotImplementedError

class MyClass(IInterface):
    def show(self): print "Hello World!"
Bandi-T
What should I do about `__init__(self)` the constructor?
TheMachineCharmer
Up to you. Since there is no compile-time check against constructing an object from an abstract class you would not gain any protection during coding/compiling. There will be a constructor inherited, so the object *would* get created, just be "empty". It is up to you to decide whether you'd be better off by allowing this to happen and catch failures later, or explicitly stop the program right then and there by implementing a similar constructor throwing an exception.
Bandi-T
+1  A: 

My understanding is that interfaces are not that necessary in dynamic languages like Python. In Java (or C++ with its abstract base class) interfaces are means for ensuring that e.g. you're passing the right parameter, able to perform set of tasks.

E.g. if you have observer and observable, observable is interested in subscribing objects that supports IObserver interface, which in turn has notify action. This is checked at compile time.

In Python, there is no such thing as compile time and method lookups are performed at runtime. Moreover, one can override lookup with _getattr_() or _getattribute_() magic methods. In other words, you can pass, as observer, any object that can return callable on accessing notify attribute.

This leads me to the conclusion, that interfaces in Python do exist - it's just their enforcement is postponed to the moment in which they are actually used

Tomasz Zielinski
+4  A: 

As mentioned by other here:

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.

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.

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!

Lennart Regebro