【发布时间】: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