overriding methods - two questions

George Sakkis george.sakkis at gmail.com
Fri Nov 16 21:30:28 EST 2007


On Nov 16, 5:03 pm, Steven D'Aprano <st... at REMOVE-THIS-
cybersource.com.au> wrote:

> On Fri, 16 Nov 2007 18:28:59 +0100, Bruno Desthuilliers wrote:
> >> Question 1:
>
> >> Given that the user of the API can choose to override foo() or not, how
> >> can I control the signature that they use?
>
> > 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. Why do you
> want to stop them?

Primarily because of this: http://en.wikipedia.org/wiki/Liskov_substitution_principle.

> Let me give a practical example:
>
> (snip misleading example involving __init__)

Constructors are in general different from other regular methods
because you refer explicitly to the class name when creating an
instance; that is, the client writes "f = ContinuedFraction(...)" or
"f = RegularCF(...)" so it's not necessary to have the same signature
in __init__. For all other methods though, given that you have an
instance x so that isinstance(x, ContinuedFraction), the client should
be able to say x.foo(arg, kwd=v) without having to know whether
x.__class__ is ContinuedFraction. If not, you have a leaky abstraction
[1], i.e. in your example, a RegularCF is not really a
ContinuedFraction.

George


[1] http://www.joelonsoftware.com/articles/LeakyAbstractions.html



More information about the Python-list mailing list