以类装饰器风格编写一个函数来为您执行复制。在Python2.5中,您可以在创建类后直接应用它。在更高版本中,您可以使用@decorator表示法。
这是如何做到的第一步:
import types
def fix_docs(cls):
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
print func, 'needs doc'
for parent in cls.__bases__:
parfunc = getattr(parent, name, None)
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
return cls
class Animal(object):
def walk(self):
'Walk like a duck'
class Dog(Animal):
def walk(self):
pass
Dog = fix_docs(Dog)
print Dog.walk.__doc__
在较新的Python版本中,最后一部分更加简单美观:
@fix_docs
class Dog(Animal):
def walk(self):
pass
这是一项Pythonic技术,与标准库中现有工具的设计完全匹配。例如,functools.total_ordering 类装饰器向类添加缺少的丰富比较方法。再举一个例子,functools.wraps 装饰器将元数据从一个函数复制到另一个函数。