overriding methods - two questions
Bruno Desthuilliers
bruno.42.desthuilliers at wtf.websiteburo.oops.com
Fri Nov 16 12:28:59 EST 2007
Donn Ingle a écrit :
> Hi,
> Here's a framework for the questions:
>
> --- In a module, part of an API ---
> class Basis ( object ):
> def foo ( self, arg ):
> pass
>
> --- In user's own code ---
> class Child ( Basis ):
> def foo ( self, not, sure ):
> ...
>
>
> 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.
> Question 2:
>
> Say I am in class Basis, doing a loop and I have a list of Child objects. I
> want to run the foo() method for each one that *has* a foo() method. i.e.
> user has done this:
>
> class Sam ( Child ):
> ...
> *Sam does not define foo()
>
> class Judy ( Child ):
> def foo ( self, arg ):
> ...
> * Judy does define foo()
>
> Instances of Sam and Judy have been put into the list (within the instance)
> of Basis. I want Basis to detect that Judy has foo() and run it.
>
> I can handle question 2 by using a flag that must be set by the user.
> Something like:
> class Judy ( child ):
> def __init__( self ):
> self.pleaseCallFoo = true
>
> And now, Basis can check for that var and only then call foo(), but this is
> ugly and means more for the user to learn API-wise.
Indeed.
> Any ideas?
Quite a few, but I don't have enough context to tell which one would be
the best - nor why you want to do such a thing. Anyway, the simplest is
to just check :
for child in self.childrens:
if 'foo' in child.__class__.__dict__:
child.foo()
but this won't call foo for :
class Dude(Judy):
pass
Don't know if that's what you want. If not (ie, you want to call
child.foo if foo is not Basis.foo), then:
for child in self.childrens:
if child.foo.im_func is not self.foo.im_func:
child.foo()
HTH
More information about the Python-list
mailing list