inheritance and default arguments
Andrew Koenig
ark at research.att.com
Sun Aug 11 11:47:55 EDT 2002
I want a method in a class hierarchy to have a default argument. For
example, I might want the method to deal with a designated substring
of a string that I pass as an argument, and I want the beginning and
end of the substring to be 0 and len(s) as defaults.
I can't do this:
class Base(object):
def f(self, s, begin=0, end=len(s)):
...
class Derived(object):
def f(self, s, begin=0, end=len(s)):
...
because the default argument is evaluated at the wrong time.
If I fix this problem in the obvious way:
class Base(object):
def f(self, s, begin=0, end=None):
if end == None:
end = len(s)
...
class Derived(base):
def f(self, s, begin=0, end=None):
if end == None:
end = len(s)
...
I must now repeat not only the default arguments, but also the
corresponding tests, in each derived class.
I can avoid that repetition by splitting the function into two:
One deals with the default-argument processing (and is inherited
by every derived class), the other does the actual work (and is
overridden as needed in the derived classes):
class Base(object):
def f(self, s, begin=0, end=None):
if end == None:
end = len(s)
return self.f_aux(s, begin, end)
def f_aux(self, s, begin, end):
...
class Derived(object):
def f_aux(self, s, begin, end):
...
This isn't too bad, but I have the feeling that there may be a more
Pythonic way of doing the same thing.
Any suggestions?
--
Andrew Koenig, ark at research.att.com, http://www.research.att.com/info/ark
More information about the Python-list
mailing list