【问题标题】:Using overloaded method in parent class在父类中使用重载方法
【发布时间】:2021-01-14 05:25:53
【问题描述】:

考虑以下代码:

class iterative_solver:

   def stop_condition(self):
   #To be specified in the child classes

   def solver(self):
      while stop_condition:                   #Error
         print("In the cycle")

class specific_solver(iterative_solver):

   def stop_condition(self,num):
      return num>0

当我定义方法stop_condition时,我还不知道它可能需要什么参数,我将方法的具体实现留在子类specific_solver中。

如何在父类中使用在子类中指定的方法,但我还不知道其参数?

【问题讨论】:

  • solver 方法应该如何工作?里面没有任何东西可以改变条件的结果。
  • 您需要为stop_condition()定义一个接口并在solver()方法中使用它。可以通过使用可变长度 *args 和 *kwargs` 参数使其相当通用。
  • 您是否有与已经给出的答案不同的特定方法?我正在学习Python和OOP编程,所以我一点经验都没有
  • 也许你想要做的一个更实际的例子会产生其他答案。目前,您的问题很抽象。

标签: python inheritance polymorphism


【解决方案1】:

解决方案

使用*args**kwargs 允许传递任意参数和关键字参数。

示例

class IterativeSolver(object):

   def stop_condition(self):
       raise NotImplementedError # Use this to indicate that subclass must override the method.

   def solver(self, *args, **kwargs):
      while stop_condition(*args, **kwargs):
         print("In the cycle")

class SpecificSolver(IterativeSolver):

   def stop_condition(self, num):
      return num>0

num = 1
SpecificSolver.solver(num)

【讨论】:

  • 谢谢,我明白了。但是,有几个问题:(1)代码没有运行,你能发布一个正常运行的版本吗? (2) 假设我现在有stop_condition1stop_condition2,子类可以覆盖并且我想在solver 中使用它们。有没有一种很好的方法来区分 *args 的哪些部分进入 stop_condition (1 或 2)?我认为将每个输入都放入solver 方法会使事情变得更加混乱,再次感谢您:)
猜你喜欢
  • 1970-01-01
  • 2019-05-18
  • 2021-11-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多