简体   繁体   English

有关要返回的对象类型的Python文档字符串

[英]Python docstring about the type of object being returned

class Foo:
    def __init__(self, bar):
        self.bar = bar

    def get_new_foo(self, new_bar):
        return type(self)([self.bar, new_bar]) #How should it be documented?

If get_new_foo gets called from a derived class, then it would return an instance of the derived class. 如果从派生类调用get_new_foo ,则它将返回派生类的实例。 If multiple classes use Foo as base class, then get_new_foo will return an instance of the derived class it was called from. 如果多个类使用Foo作为基类,则get_new_foo将返回其派生类的实例。

I want to document what type of object get_new_foo returns, and I don't understand what/how to document it. 我想记录get_new_foo返回什么类型的对象,但我不知道记录什么/如何记录。 I can't say Returns an instance of Foo because this will not be the case always. 我不能说Returns an instance of Foo因为并非总是如此。

Personally, I wouldn't be overly concerned about this. 就个人而言,我不会对此太过担心。 Since any subclass "is-a" Foo anyway, you're at worst mildly misleading in your chosen wording. 因为无论如何,任何子类“都是”都是Foo ,所以最糟糕的是,您在选择的措词上会产生轻微的误导。 If you want to be pedantically correct, you can always expand it to "Returns an instance of Foo (a Foo subclass when called on child class instances)". 如果您想得到正确的信息,可以始终将其扩展为“返回Foo的实例(在子类实例上调用时为Foo子类)”。

You can provide type hints in the docstring. 您可以在文档字符串中提供类型提示。

Since you're writing the documentation on a class that would be the super-class for other classes, it makes sense that you document the base type it returns. 由于您是在一个类(该类将是其他类的超类)上编写文档的,因此您可以对返回的基本类型进行文档化。 Even if the actual type that will be returned once the base class is inherited, the results will still be instances of the base type and at this level, you cannot document anything beyond that anyway. 即使继承了基类后将返回的实际类型,结果仍将是该基本类型的实例,并且在此级别上,您无论如何都无法记录任何内容。

If you feel sub-classes need more specific documentation for whatever they return, you can simply provide the documentation there. 如果您觉得子类返回的内容需要更具体的文档,则只需在此处提供文档即可。

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

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