callable virtual method

Dave Angel davea at ieee.org
Fri Aug 14 15:24:39 EDT 2009


Jean-Michel Pichavant wrote:
> <div class="moz-text-flowed" style="font-family: -moz-fixed">Nigel 
> Rantor wrote:
>> Jean-Michel Pichavant wrote:
>>>
>>> Your solution will work, for sure. The problem is that it will dumb 
>>> down the Base class interface, multiplying the number of methods by 
>>> 2. This would not be an issue in many cases, in mine there's already 
>>> too much meaningful methods in my class for me to add artificial ones.
>>>
>>> Thanks for the tip anyway.
>>
>> I suggest you reconsider.
>>
>> You asked a question and have been given a standard way of achieving 
>> the desired outcome.
>>
>> It's common in OO to use a Template pattern like this.
>>
>> If you're not interested in finding out how loads of people have 
>> already solved the problem then why ask?
>>
>> The methods that require overriding can be prefixed with an 
>> underscore so that people get a hint that they are an implementation 
>> detail rather than part of the public interface.
>>
>> I don't see your problem, other than a vague aesthetic unease.
>>
>> Regards,
>>
>>   n
> I understand how refuting some obvious solution may look just stupid. 
> You're right, I shouldn't have asked.
>
> By the way I'd like to know if I am I alone to find that
>
> class Stream:
>    def start
>    def stop
>    def reset
>
> is better than
>
> class Stream:
>    def start
>    def _start
>    def stop
>    def _stop
>    def reset
>    def _reset
>
> (try to figure out with 20+ methods)
> What you call aesthetic may sometimes fall into readability.
>
>
> JM
>
>
> </div>
>
Usually when one defines an abstract base class, one expects many people 
will derive from it, as opposed to only one having to write it.  So if 
the base must be "ugly" according to some definition, so be it.  
Aesthetics are quite subjective.

Nigel's approach has another benefit not stated, which is to keep the 
child class code simpler.  They avoid the need to call any base class 
method to access the common logic.  The downside is it assumes that the 
common logic will always be either at the beginning or always at the end 
of the child classes implementation.  That's because the base class has 
hardcoded where in its implementation to call the child class method.

Anyway, without arguing for or against either approach, I'd point out 
that you could have an extra formal parameter in the base method, which 
is a private signal from the child class that this is the internal 
call.  Missing such a formal parameter would then trigger the "missing 
method in derived class" error message.  You'd check such a parameter 
the same place as you're now checking the object's type.

DaveA





More information about the Python-list mailing list