简体   繁体   English

附加到继承的方法文档字符串

[英]Appending to inherited method docstring

I'm trying to define a subclass that only changes the __init__ method, that change will change the behavior of some of the methods and I wanted to be able to update the docstrings accordingly.我正在尝试定义一个仅更改__init__方法的子类,该更改将更改某些方法的行为,并且我希望能够相应地更新文档字符串。 I have been trying something like this:我一直在尝试这样的事情:

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"

However, by doing this I change the docstring for the return_x method in the parent class as well:但是,通过这样做,我也更改了父类中return_x方法的文档字符串:

>>> x = ParentClass()
>>> help(x.return_x)
    "Will return 2 now"
>>> x = ChildClass()
>>> help(x.return_x)
    "Will return 2 now"

I tried other variations to this, but it either led to an error or changed the Parent Class docstring as well.我尝试了其他变体,但它要么导致错误,要么也更改了父类文档字符串。 Is there any simple way that I can change the child class docstring without having to redefine the method?有什么简单的方法可以更改子类文档字符串而无需重新定义方法?

Edit 1 , In response to @Anonymous12358 comment:编辑 1 ,回应@Anonymous12358 评论:

My intention in not needing to redefine the method is to avoid repetition of a complicated method signature and a relatively long documentation.我不需要重新定义方法的目的是避免重复复杂的方法签名和相对较长的文档。 In my real case the change to the documentation can be made by simply appending a sentence to the end of the original documentation.在我的真实案例中,只需在原始文档的末尾附加一个句子即可对文档进行更改。 So I'm looking for an implementation similar to:所以我正在寻找类似于以下的实现:

ChildClass.return_x.__doc__ += "\n Appended sentence to the doc"

You could override the return_x method in the child class with an explicit foward to the super , and write a docstring for the override:您可以通过显式转发到super来覆盖子类中的return_x方法,并为覆盖编写一个文档字符串:

class ChildClass(ParentClass):
    ...
    def return_x(self):
        """Will return 2"""
        return super().return_x()

The subclass will still always have the same behaviour as its parent, but now has its own version of the method and therefore its own docstring.子类仍将始终具有与其父类相同的行为,但现在拥有自己的方法版本,因此拥有自己的文档字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM