简体   繁体   中英

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. 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:

>>> 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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