callable virtual method

Diez B. Roggisch deets at nospam.web.de
Fri Aug 14 17:50:47 CEST 2009


Jean-Michel Pichavant schrieb:
> Hi fellows,
> 
> Does anyone know a way to write virtual methods (in one virtual class) 
> that will raise an exception only if called without being overridden ?
> Currently in the virtual method I'm checking that the class of the 
> instance calling the method has defined that method as well.
> 
> Example:
> 
> class Stream(object):
>    """Interface of all stream objects"""
>    def resetStats(self):
>        """Reset the stream statistics. All values a zeroed except the 
> date."""
>        _log.info('Reset statistics of %s' % self)
>        if self.__class__.resetStats == Stream.resetStats:
>            raise NotImplementedError()
> 
> It works but it's tedious, I have to add these 2 lines to every virtual 
> method, changing the content of the 2 lines.
> 
> Maybe there is a nice/builtin way to do so (python 2.4)

Python has no concept of "virtual" methods. A simple


class Stream(object):


    def resetStats(self):
        raise NotImplemented


is all you need. Once a subclass overrides resetStats, that 
implementatino is used.

Additionally, there are modules such as zope.interface out there, that 
let you define more formally what an interface is, and declare who's 
implementing it. I don't used this myself though, so I can't really 
comment to which extend it e.g. warns you if you subclass *without* 
implementing.

Diez



More information about the Python-list mailing list