我有以下对象,在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.__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
是一个长方法,并且我想在子类中更改的只是docstring,该怎么办
这是因为您没有重写children类中的方法。因此,首先,如果您调用
Hybrid.drive
这与Car.drive
完全相同的方法,那么无论您从哪个类访问它,都只存在一个方法如果重写它们,将得到不同的方法,每个方法都有自己的文档字符串
相关问题 更多 >
编程相关推荐