【问题标题】:Python -Passing a class method as the default value of an argument to another class initializationPython - 将类方法作为参数的默认值传递给另一个类初始化
【发布时间】:2017-02-27 03:31:59
【问题描述】:

修改原始问题以防止混淆。我在 2 个不同的模块中定义了 2 个类:

class Heuristic:
    def process(self,data,x,y):
        processed_data = (data + x) /y 
        return processed_data

class GTS(Abstract_Strat):
    def __init__(self, data, method= Heuristic().process(),*args):
        self.data= data
        self.method = method
        self.func_args = args

所以在 GTS 类中,在初始化函数中,我试图传递一个属于另一个模块中的启发式类的方法。尝试此操作时,我收到以下错误:

TypeError: process() takes exactly 3 arguments (1 given)

我搜索了stackoverflow,发现Typerror提到_init_方法的类似问题。但在这种情况下,错误是针对作为参数传入_init_ 方法的函数。所以问题是-将一个类的方法作为默认参数值传递给另一个类的初始化程序的正确方法是什么?

【问题讨论】:

  • Heuristic().process().
  • 谢谢,这有帮助,但现在它说:TypeError: __init__() 只需要 2 个参数(1 个给定)
  • Heuristic 的初始化程序中有 data 参数。 Heuristic(data_here).process()
  • 知道了,所以这两个类中的“数据”参数应该是相同的。所以我想出路是从初始化程序中删除数据并转移到其他类方法?

标签: python class methods parameter-passing typeerror


【解决方案1】:

在python中,你必须先构造一个类的实例,然后才能访问一个对象,然后是它的方法。

你可能会这样做:

class GTS(Abstract_Strat):
    heuristic = Heuristic(data)
    def __init__(self, data, method= heuristic.process(),*args):
        self.data= data
        self.method = method
        self.func_args = args

从而构造您的对象并让您访问它的“绑定”方法。它引用的第一个参数是定义中的“self”,在它是类的实例被初始化之前,您无法访问它。

【讨论】:

    【解决方案2】:

    我通过将Heuristic().process() 更改为Heuristic().process 将其作为函数参数的默认值传递,从而解决了上面修改后的问题中提到的问题。

    还要感谢 Andrew 对问题的原始版本的评论。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-18
      • 2023-01-18
      • 2020-03-14
      • 2013-10-13
      相关资源
      最近更新 更多