问题描述
我在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.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}.