提议的装饰器here能够继承方法的文档字符串,但不能继承属性和getter。
我试图天真地扩展它,但似乎属性的docstrings是只读的。有没有办法继承那些?
import types
def fix_docs(cls):
for name, func in vars(cls).items():
if isinstance(func, (types.FunctionType, property)) 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 X(object):
"""
some doc
"""
angle = 10
"""Not too steep."""
def please_implement(self):
"""
I have a very thorough documentation
:return:
"""
raise NotImplementedError
@property
def speed(self):
"""
Current speed in knots/hour.
:return:
"""
return 0
@speed.setter
def speed(self, value):
"""
:param value:
:return:
"""
pass
@fix_docs
class SpecialX(X):
angle = 30
def please_implement(self):
return True
@property
def speed(self):
return 10
@speed.setter
def speed(self, value):
self.sp = value
help(X.speed)
help(X.angle)
help(SpecialX.speed)
help(SpecialX.ange)
这只能让我
Traceback (most recent call last):
<function please_implement at 0x036101B0> needs doc
<property object at 0x035BE930> needs doc
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.2\helpers\pydev\pydevd.py", line 1556, in <module>
globals = debugger.run(setup['file'], None, None, is_module)
File "C:\Program Files (x86)\JetBrains\PyCharm Community Edition 2016.2\helpers\pydev\pydevd.py", line 940, in run
pydev_imports.execfile(file, globals, locals) # execute the script
File "C:/Users/RedX/.PyCharm2016.2/config/scratches/scratch.py", line 48, in <module>
class SpecialX(X):
File "C:/Users/RedX/.PyCharm2016.2/config/scratches/scratch.py", line 10, in fix_docs
func.__doc__ = parfunc.__doc__
TypeError: readonly attribute
答案 0 :(得分:0)
是的,属性docstrings是只读的。你必须建立一个新的财产:
replacement = property(fget=original.fget,
fset=original.fset,
fdel=original.fdel,
__doc__=parentprop.__doc__)
并用原来替换原件。
替换原始函数的文档字符串然后重新生成属性以自动传递它可能稍微好一些:
original.fget.__doc__ = parentprop.__doc__
replacement = property(fget=original.fget,
fset=original.fset,
fdel=original.fdel)
答案 1 :(得分:0)
此版本支持多重继承,并使用Expected behavior: (str "hello " "there") => "hello there"
Actual behavior: (str "hello " "there") => "hello there"
代替__mro__
从基础文件复制文档。
__bases__
试验:
def fix_docs(cls):
"""
This will copy all the missing documentation for methods from the parent classes.
:param type cls: class to fix up.
:return type: the fixed class.
"""
for name, func in vars(cls).items():
if isinstance(func, types.FunctionType) and not func.__doc__:
for parent in cls.__bases__:
parfunc = getattr(parent, name, None)
if parfunc and getattr(parfunc, '__doc__', None):
func.__doc__ = parfunc.__doc__
break
elif isinstance(func, property) and not func.fget.__doc__:
for parent in cls.__bases__:
parprop = getattr(parent, name, None)
if parprop and getattr(parprop.fget, '__doc__', None):
newprop = property(fget=func.fget,
fset=func.fset,
fdel=func.fdel,
parprop.fget.__doc__)
setattr(cls, name, newprop)
break
return cls