Inheriting methods but over-riding docstrings

Gerard Flanagan grflanagan at gmail.com
Sat Jan 16 14:02:47 EST 2010


Steven D'Aprano wrote:
> 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?
> 
> 
> 

If I've understood, one idea is:

------------------------------
def type_factory(colour):

     class Base(object):

         def parrot(self):
             """Norwegian %s"""
             return 1
         parrot.__doc__ %= colour

     return Base

class Base(object):

     def __new__(cls, *args, **kw):
         return type_factory(cls.colour)(*args, **kw)


class A(Base):
     colour = "Blue"

class B(Base):
     colour = "Red"

a = A()
b = B()

print inspect.getdoc(a.parrot)
Norwegian Blue
print inspect.getdoc(b.parrot)
Norwegian Red
----------------------------------------------

In the more general case, (ie. where you don't know that there is a 
method called parrot and an attribute called colour), I imagine you 
could do the same thing but at the metaclass level.

HTH

G.F.




More information about the Python-list mailing list