callable virtual method

Jean-Michel Pichavant jeanmichel at sequans.com
Fri Aug 14 22:22:10 CEST 2009


Steven D'Aprano wrote:
> On Fri, 14 Aug 2009 18:49:26 +0200, Jean-Michel Pichavant wrote:
>
>   
>> Sorry guys (means guys *and* gals :op ), I realized I've not been able
>> to describe precisely what I want to do. I'd like the base class to be
>> virtual (aka abstract). However it may be abstract but it does not mean
>> it cannot do some usefull stuff.
>>
>>
>> Here is the schema of my abstract methods :
>>
>> class Interface(object):
>>     def method(self):
>>         # ---------------------
>>         # some common stuff executed here
>>         # ---------------------
>>         print 'hello world'
>>         # ---------------------
>>         # here shall stand child specific stuff (empty in the interface
>> method)
>>         # ---------------------
>>         if self.__class__.method == Interface.method:
>>             raise NotImplementedError('You should have read the f******
>> manual ! You must override this method.')
>>     
>
>
> Okay, so I want to sub-class your Interface class. As you said, the 
> methods in the abstract class are still useful, so in my class, I don't 
> need any extra functionality for some methods -- I'm happy with just the 
> "common stuff". So I use normal OO techniques and over-ride just the 
> methods I need to over-ride:
>
>   
Sometimes the base is doing cool stuff but incomplete stuff which 
requires knowledge only hold by the sub class. In my case the interface 
is a high level interface for a software that can run on multiple 
hardware platforms. Only the sub class has knowledge on how to operate 
the hardware, but no matter the hardware it still produces the same effect.

Let's say I have 50 different hardwares, I'll have 50 sub classes of 
Interface with the 'start' method to define. It wouldn't be appropriate 
(OO programming)to write 50 times '_log.debug('Starting %s' % self)' in 
each child start method when the simple task of logging the call can be 
nicely handled by the base class.

In the meantime, I must make sure  the user, who is not a python guru in 
this case, has implemented the start method for his hardware, because 
only him knows how to effectively start this hardware. I don't want him 
to come to me saying, "I got no error, still my hardware does not 
start". You can then blame him for not reading the docs, but it will 
still be less expensive to throw a nice exception with an accurate feedback.

[snip]
> class VerboseGoodChild(Interface):
>     # forced to over-ride methods for no good reason
>   

Definitely no !! This is the purpose of an interface class: to force 
people to write these methods. They *are* required, if they were not, 
they would not belong to the Interface.

JM



More information about the Python-list mailing list