Inheriting methods but over-riding docstrings
Gabriel Genellina
gagsl-py2 at yahoo.com.ar
Sun Jan 17 13:02:23 EST 2010
En Sat, 16 Jan 2010 14:55:11 -0300, Steven D'Aprano
<steve at remove-this-cybersource.com.au> escribió:
> I have a series of subclasses that inherit methods from a base class, but
> I'd like them to have their own individual docstrings. The obvious
> solution (other than copy-and-paste) is this:
>
>
> class Base(object):
> colour = "Blue"
> def parrot(self):
> """docstring for Base"""
> return "Norwegian %s" % self.colour
>
>
> class SubClass(Base):
> colour = "Red"
> def parrot(self):
> """docstring for Subclass"""
> return super(Subclass, self).parrot()
>
>
> but that adds an awful lot of boilerplate to my subclasses. Are there any
> other good solutions to this problem?
Methods don't have docstrings; functions do. So one has to "clone" the
function to set a new docstring.
<code>
def copy_function(fn, docstring):
fn = getattr(fn, "im_func", fn) # accomodate unbound methods in 2.x
function_type = type(lambda:0)
newfn = function_type(fn.__code__, fn.__globals__, fn.__name__,
fn.__defaults__, fn.__closure__)
newfn.__doc__ = docstring
return newfn
class Base(object):
colour = "Blue"
def parrot(self):
"""docstring for Base"""
return "Norwegian %s" % self.colour
class SubClass(Base):
colour = "Red"
parrot = copy_function(Base.parrot, "docstring for Subclass")
</code>
py> x = Base()
py> print(x.parrot())
Norwegian Blue
py> print x.parrot.__doc__
docstring for Base
py> y = SubClass()
py> print(y.parrot())
Norwegian Red
py> print y.parrot.__doc__
docstring for Subclass
--
Gabriel Genellina
More information about the Python-list
mailing list