如何在python中为继承的方法格式化docstring?
我在如何在python中为继承的方法格式化docstring?,python,string,inheritance,format,docstring,Python,String,Inheritance,Format,Docstring,我在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 pl
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
的docstring是用“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.\uuuuu doc\uuuu=Car.drive.\uuuu doc\uuuu.format('Van')
正在更改字符串Car.drive.\uuuuu doc\uuu.format('Van')
。这一点已得到证实
cars.Car.drive.__doc__
> "This is the docstring for how to drive a van."
如何格式化混合动力.drive的字符串。\uuuu doc\uuuu
“这是如何驱动混合动力的docstring”
编辑:
虽然在子类中重写
drive
方法可以工作,但是如果drive
是一个长方法,而我想在子类中更改的只是docstring呢?这是因为您没有重写子类中的方法。因此,首先,如果调用Hybrid.drive
,这是与Car.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}.
虽然这在这里是可行的,但是如果drive是一个长方法,而我想在子类中更改的只是docstring呢?@NewNameStat想想这个意思,为什么要为完全相同的方法提供不同的docstring呢?如果不重写该方法,则docstring应该是“。。。关于如何驾驶汽车,没有确切的说明是哪种类型的汽车,因为该方法是为一种Hehicule而设计的,我明白你的意思,但我只是想为完全相同的方法提供一个不同的文档字符串。不重写该方法是否可行?@NewNameStat我不这么认为,我有关于该方法的更多信息,我已经对缺少的答案发表了评论。我很感激你的帮助,但我不认为这个问题是“回答”的。