Interface Implementation in Python

p_shakil at yahoo.com p_shakil at yahoo.com
Tue Mar 6 19:23:59 EST 2007


On Mar 6, 11:55 am, "Goldfish" <gregt... at mindspring.com> wrote:
> > >  I would like to know the interface concept in Python.How the
> > > Interface is defined and implemented in Python?.
>
> One way I have implemented interfaces, is as follows:
>
> class MyInterface(object):
>     def someMethod(self, argument):
>         raise NotImplementedError()
>
> If anybody ever uses that class directly, or subclasses it without
> implementing a real version of that method, a runtime error can be
> expected. This bridges both interfaces and abstract classes.
>
> As others have pointed out, this isn't quite like a Java interface,
> but I have found it useful to state my intentions up front, and that
> is how I do it. The only way to truly enforce this is by following up
> with lots of good test cases, run often.


I have a class by name Point3D in Python.

class Point3D :
def __int(self):
self.__x =0.0
self.__y =0.0
self.__z =0.0

def setPoint(x,y,z):
self.__x =x
self.__y =y
self.__z =z

def getPoint(x,y,z):
x = self.__x
y = self.__y
z = self.__z

I dont want to expose the above Point3D implementation to the user /
client side.To achieve that we can use interface concept.In Python to
use interface concept.

How the interface class looks like for Point3D in python?.

How to implement that Interface?

How to access the implemented interface thru Interface Object in the
client side?

It will be helpful if somebody proivide a piece of sample code for
creating the interface for the above access at the client place

in C++ these can be done in this way

class IPoint : public IUnknown{
virtual void setPoint(int x,int y,int z)=0;
virtual void getPoint(&x,&y,&z)=0;
}

class Point3D: public IPoint {
private :
float _x ,_y,_z;
public:
void Point3D() {
_x=_y=_z =0
}
void setPoint(int x,int y,int z){

_x =x
_y =y
_z =z


}
void getPoint(&x,&y,&z){
x = _x
y = _y
z = _z
}
}

Access the Point data in the client side

IPoint *pIPoint = NULL;
pISampleInterface = CoCreateInstance(..);
...............
pISampleInterface ->QueryInstance(IID_IPoint ,(void*&)pIPoint )

// We have the pIPoint interafce
float dX =0,dY=0,dZ=0;

pIPoint->setPoint(10,20,30);

pIPoint->getPoint(&dX ,&dY,&dZ);

printf ( "%f,%f%f",dX ,dY,dZ);

10.0 20.0 30.0


Thanks
PSB

--------------------------------------------------------------------------------






More information about the Python-list mailing list