如何在Python中更改继承方法的文档字符串?

时间:2019-03-15 16:40:35

标签: python inheritance docstring

假设我具有如下所示的类结构:

class BaseClass(object):
  def divide_reward_by_x(self, x, data):
    """
    Args:
      x: float
    Return:
      Reward value
    """
    return self.reward(data) // x

class SubClass1(BaseClass):
  def reward(self, data):
    """
    Args:
      data: one-dimensional numpy array
    Return:
      float of reward value
    """
    return np.sum(data)

class SubClass2(BaseClass):
  def reward(self, data):
    """
    Args:
      data: one-dimensional numpy array
    Return:
      one-dimensional numpy array of reward value
    """
    return data + 1

请注意,SubClass1的reward返回一个浮点数,而SubClass2的reward返回一个numpy数组。这意味着当为SubClass1调用divide_reward_by_x时,它将返回一个浮点数,而当为SubClass2调用时,它将返回一个numpy数组。我希望SubClass文档能够反映这一点。换句话说,代码本身不是特定于子类的,而是文档应该是!

以最少的文档和代码重复来完成此操作的最Python方式是什么?

我知道以下解决方案,但我想知道是否还有更多的“极简主义”和“ pythonic”方式:

class BaseClass(object):
  def _divide_reward_by_x(self, x, data):
    return self.reward(data) // x

class SubClass1(BaseClass):
  def reward(self, data):
    """
    Args:
      data: one-dimensional numpy array
    Return:
      float of reward value
    """
    return np.sum(data)

  def divide_reward_by_x(self, x, data):
    """
    Args:
      x: float
    Return:
      Float of reward value
    """
    return self._divide_reward_by_x(x, data)

class SubClass2(BaseClass):
  def reward(self, data):
    """
    Args:
      data: one-dimensional numpy array
    Return:
      one-dimensional numpy array of reward value
    """
    return data + 1

  def divide_reward_by_x(self, x, data):
    """
    Args:
      x: float
    Return:
      numpy array of reward value
    """
    return self._divide_reward_by_x(x, data)

0 个答案:

没有答案