python-3.x 是否可以在子类上显示__init_subclass__ docstring?

biswetbf  于 2023-01-06  发布在  Python
关注(0)|答案(1)|浏览(126)

假设我有一个类,它用两个参数实现了__init_subclass__:

class Foo:

    def __init_subclass__(name: str, surname: str):
        """
        name: The name of the user
        surname: The surname of the user
        """
        ...

当我从Foo子类化时,我希望能够在子类化类的docstring中看到两个参数(name,surname)的描述。有什么方法可以实现这一点吗?这样当用户从Foo子类化时,他就知道在类的参数中放置什么了

class Bar(Foo, name = 'bar', surname = 'xxx')
    ...
gab6jxml

gab6jxml1#

我不是很确定,我理解的没错,但是要将__init_subclass__的文档添加到Foo的子类中,您可以更新子类__doc__

class Foo:
    def __init_subclass__(cls, name: str, surname: str, **kwargs):
        """
        name: The name of the user
        surname: The surname of the user
        """
        cls.__doc__ = Foo.__init_subclass__.__doc__ + cls.__doc__

class Bar(Foo, name='bar', surname='xxx'):
    """Docs of Bar"""

然后

>>> print(Bar.__doc__)

        name: The name of the user
        surname: The surname of the user
        Docs of Bar

相关问题