overriding methods - two questions

Donn Ingle donn.ingle at gmail.com
Fri Nov 16 12:03:53 EST 2007


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? In the example the user has chosen
bad arguments and Python will complain, but it's describing the sig of the
*overridden* method and not the one in the parent class.

 Is there some way I can control the error message to make it clear to the
user that they are using the signature of foo() incorrectly?

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.

Any ideas?
/d





More information about the Python-list mailing list