can i implement virtual functions in python ?

logistix at cathoderaymission.net logistix at cathoderaymission.net
Tue Sep 30 17:32:02 EDT 2003


prabua at hotmail.com (Prabu) wrote in message news:<e73c30c6.0309300653.24456567 at posting.google.com>...
> Hi,
> 
> I'm new to python, so excuse me if i'm asking something dumb. 
> Does python provide a mechanism to implement virtual functions?
> Can you please give a code snippet also...:)
> Thanx in advance
> -Prabu.

As others have mentioned, all methods are overridable in python.  But
if you want to create a genuine Abstract Base Class, raise
NotImplementedErrors for the virual methods.  People will tell you
that this is not 'pythonic' (you should be using hasattr() to test for
interfaces) but I still find it useful from time to time.

PythonWin 2.3.2c1 (#48, Sep 30 2003, 09:28:31) [MSC v.1200 32 bit
(Intel)] on win32.
Portions Copyright 1994-2001 Mark Hammond (mhammond at skippinet.com.au)
- see 'Help/About PythonWin' for further copyright information.
>>> class virtualClass:
...     def __init__(self):
...         pass
...     def virtualMethod1(self):
...         raise NotImplementedError("virtualMethod1 is virutal and
must be overridden.")
...     def concreteMethod1(self):
...         print "The concrete method is implemented"
... 
		
>>> x = virtualClass()

>>> x.concreteMethod1()
The concrete method is implemented

>>> x.virtualMethod1()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
  File "<interactive input>", line 5, in virtualMethod1
NotImplementedError: virtualMethod1 is virutal and must be overridden.

>>> class subClass(virtualClass):
...     def virtualMethod1(self):
...         print "sub class implemented virtualMethod1"
... 
		
>>> y = subClass()

>>> y.concreteMethod1()
The concrete method is implemented

>>> y.virtualMethod1()
sub class implemented virtualMethod1

>>>




More information about the Python-list mailing list