如何在python中为继承的方法格式化docstring?

2024-05-14 04:19:39 发布

您现在位置: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的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,该怎么办


Tags: thetoformatfordocisdrivethis
1条回答
网友
1楼 · 发布于 2024-05-14 04:19:39

这是因为您没有重写children类中的方法。因此,首先,如果您调用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}.

相关问题 更多 >