overriding methods - two questions

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Nov 17 09:18:10 CET 2007


On Sat, 17 Nov 2007 06:47:18 +0200, Donn Ingle wrote:

>>> While technically possible (using inspect.getargspec), trying to make
>>> your code idiot-proof is a lost fight and a pure waste of time.
>  
>> Worse: it's actually counter-productive! The whole idea of being able
>> to subclass a class means that the user should be able to override
>> foo() *including* the signature.
>
> Steven,
>  In this case, the def in question is named Draw. It's args are context
>  and
> framenumber. The body is 'pass'. I want users to use the exact signature
> (but they can change the varnames to suit) because the draw() method is
> *not* being called by the user but *by* my API (in a timeout loop).

You don't know that. How can you possibly guarantee that the user won't 
find some other use for the draw() method as well as passing it to your 
API? Maybe your application turns out to be a huge success, and people 
start extending it in all sorts of ways you never ever imagined -- or at 
least they would if you didn't needlessly lock down the classes they can 
use.

Or, if you can't imagine that, imagine that in six months time *you* 
decide to extend the application, and have another purpose for that same 
draw() callback, but need a slightly different signature.

Which suggests that maybe your API should specify keyword arguments 
rather than positional args. That way you can do something like this:

# (I'm guessing) in the main video editing loop:
blah.Draw(context=cario.context, frame=currentFrame)

# we want to display the third frame as we draw
blah.Draw(context=another_context, frame=3, window=preview)

# don't forget to flip the title frame
blah.Draw(flip=True, context=cairo.context, frame=title)


BTW, it is a convention for method names to be lower case, and classes to 
be Title case. Seeing something like obj.Draw, most(?) Python developers 
will expect that the Draw attribute of obj is itself a class:

>>> class MyClass(object):
...     class Draw(object):
...         pass
...
>>> x = MyClass()
>>> x.Draw
<class '__main__.Draw'>


-- 
Steven.



More information about the Python-list mailing list