如何在python中格式化继承方法的文档字符串?

问题描述

我在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一个方法,而我想在子类中更改的只是文档字符串怎么办?

解决方法

这是因为您没有覆盖子类中的方法。因此,一开始,如果调用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}.

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...