【问题标题】:How to format the docstring for inherited methods in python?如何格式化python中继承方法的文档字符串?
【发布时间】:2021-01-17 14:49:49
【问题描述】:

我有以下对象,在cars.py

import abc

class Car(abc.ABC):

  def drive(self):
    """This is the docstring for how to drive a {0}."""
    pass

class Van(Car):

  def shut_sliding_door(self):
    pass

class Hybrid(Car):

  def plug_in(self):
    pass

Van.drive.__doc__ = Car.drive.__doc__.format('van')
Hybrid.drive.__doc__ = Car.drive.__doc__.format('hybrid')

但是,Hybrid.drive 的文档字符串是用"van" 字符串而不是"hybrid" 字符串格式化的。

import cars as cars

cars.Hybrid.drive.__doc__
> "This is the docstring for how to drive a van."

cars.Van.drive.__doc__
> "This is the docstring for how to drive a van."

看来Van.drive.__doc__ = Car.drive.__doc__.format('van') 行正在更改字符串Car.drive.__doc__.format('van')。这得到了证实,

cars.Car.drive.__doc__
> "This is the docstring for how to drive a van."

如何将Hybrid.drive.__doc__ 的字符串格式化为"This is the docstring for how to drive a hybrid"

编辑:

虽然在子类中覆盖drive 方法可以工作,但如果drive 是一个长方法,而我想要在子类中更改它的只是文档字符串呢?

【问题讨论】:

  • 我已经评论了缺少的答案。感谢您的帮助,但我认为这个问题没有得到“回答”。

标签: python string inheritance format docstring


【解决方案1】:

那是因为你没有覆盖子类中的方法。所以一开始,如果你调用 Hybrid.driveCar.drive 完全相同的方法,那么无论你从哪个类访问它,都只存在一个方法

如果你重写它们,你会得到不同的方法,每个都有自己的,所以它自己的文档字符串

class Car(abc.ABC):
    def drive(self):
        """This is the docstring for how to drive a {0}."""
        pass

class Van(Car):
    def shut_sliding_door(self):
        pass
    def drive(self):
        pass

class Hybrid(Car):
    def plug_in(self):
        pass
    def drive(self):
        pass

if __name__ == '__main__':
    Van.drive.__doc__    = Car.drive.__doc__.format('van')
    Hybrid.drive.__doc__ = Car.drive.__doc__.format('hybrid')

    print(Van.drive.__doc__)     # This is the docstring for how to drive a van.
    print(Hybrid.drive.__doc__)  # This is the docstring for how to drive a hybrid.
    print(Car.drive.__doc__)     # This is the docstring for how to drive a {0}.

【讨论】:

  • 虽然这在这里有效,但如果驱动器是一个长方法并且我想在子类中更改它的只是文档字符串呢?
  • @NewNameStat 想一想,为什么要为 exact 相同的方法提供不同的文档字符串?如果您不覆盖该方法,则文档字符串应该是“... for how to drive a car”,并且没有确切的车辆类型,因为该方法是为一种 hehicule 构建的
  • 我明白你在说什么,但我只想说我确实想为完全相同的方法提供不同的文档字符串。是否可以不覆盖该方法?
  • @NewNameStat 我不这么认为,我有更多相关信息
猜你喜欢
  • 2011-12-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-18
  • 2016-11-30
  • 1970-01-01
  • 2012-10-06
  • 2015-01-27
相关资源
最近更新 更多