我试图定义一个只更改__init__方法的子类,该更改将改变某些方法的行为,并且我希望能够相应地更新docstring。我一直在尝试这样的方法:
class ParentClass:
def __init__(self):
"""Init docstring"""
self.x = 1
def return_x(self):
"""Will return 1"""
return self.x
class ChildClass(ParentClass):
def __init__(self):
self.x = 2
ChildClass.return_x.__doc__ = "Will return 2"但是,通过这样做,我还更改了父类中的return_x方法的docstring:
>>> x = ParentClass()
>>> help(x.return_x)
"Will return 2 now"
>>> x = ChildClass()
>>> help(x.return_x)
"Will return 2 now"我尝试了其他的变体,但是它要么导致错误,要么更改父类docstring。有什么简单的方法可以改变子类docstring而不需要重新定义方法?
编辑1,回复@Anonyous12358评论:
我不需要重新定义该方法的目的是避免重复复杂的方法签名和相对较长的文档。在我的实际案例中,对文档的更改可以简单地在原始文档的末尾加上一个句子。因此,我正在寻找一个类似于:
ChildClass.return_x.__doc__ += "\n Appended sentence to the doc"发布于 2022-07-14 19:30:23
您可以在子类中重写return_x方法,并向super发出显式提示,并为重写编写一个docstring:
class ChildClass(ParentClass):
...
def return_x(self):
"""Will return 2"""
return super().return_x()子类将始终具有与其父类相同的行为,但现在有了自己版本的方法,因此有了自己的docstring。
https://stackoverflow.com/questions/72985450
复制相似问题