Interface & Implementation

rdmurray at bitdance.com rdmurray at bitdance.com
Fri Dec 12 10:25:48 EST 2008


On Fri, 12 Dec 2008 at 16:07, J Ramesh Kumar wrote:
> I am new to python. I require some help on implementing interface and
> its implementation. I could not find any sample code in the web. Can
> you please send me some sample code which is similar to the below java
> code ? Thanks in advance for your help.
>
> ............
> public interface MyIfc
> {
>    public void myMeth1();
>    public void myMeth2();
> }
> ....
> public class MyClass implements MyIfc
> {
>      public void myMeth1()
>      {
>          //do some implementation
>      }
>
>     public void myMeth2()
>       {
>           //do some implementation
>       }
> }
> ...
>
> MyClass myc=new MyClass();
> Hashtable hash=new Hashtable();
> hash.put("MYIFC",myc);
> ........
> MyIfc myi=(MyIfc)hash.get("MYIFC");
> myi.myMeth1();
> myi.myMeth2();
> .........

The python 2.x way to to this would be:

     class MyClass(object):

         def myMeth1(self):
             #do some implementation

         def myMeth2(self):
             #do some implementation

     myc = MyClass()
     hash = dict()
     hash["MYIFC"] = myc
     myi = hash["MYIFC"]
     myi.myMeth1()
     myi.myMeth2()

Which is to say, python 2.x does not have any formal notion
of interfaces.

In python 3.0 if you have a need for an interface you can do this:

     from abc import ABCMeta, abstractmethod

     class MyIfc:
         __metaclass__ = ABCMeta

         @abstractmethod
         def myMeth1(self): pass

         @abstractmethod
         def myMeth2(self): pass


     class MyClass(MyIfc):
         [from here on just like above]

Note however, that an Abstract Base Class is _not_ the same thing
as a Java interface, though it can serve some of the same purposes.
See http://docs.python.org/dev/3.0/whatsnew/2.6.html#pep-3119 for
more.

--RDM



More information about the Python-list mailing list