Python 接受方法的构造函数

Python 接受方法的构造函数,python,constructor,Python,Constructor,在Python中,构造函数可以接受另一个类的方法作为参数吗 我听说你可以这样做,但是这个例子不起作用(目前,我得到一个'module'对象是不可调用的错误): 这里fitness是在别处定义的函数,请注意,我正在导入定义该函数的类 编辑:下面是实际产生错误的代码 class Solver( ): def __init__( self, fitness, breed, iterations ): self.T = Problem() self.fitn

在Python中,构造函数可以接受另一个类的方法作为参数吗

我听说你可以这样做,但是这个例子不起作用(目前,我得到一个'module'对象是不可调用的错误):

这里fitness是在别处定义的函数,请注意,我正在导入定义该函数的类

编辑:下面是实际产生错误的代码

class Solver( ):

    def __init__( self, fitness, breed, iterations ):

        self.T = Problem()

        self.fitness    = fitness
        self.breed      = breed
        self.iterations = iterations

    def solve( self ):
        P  = self.T.population(500)
        GA = GeneticAlgorithm(P, self.fitness, self.breed) # problem here


Traceback (most recent call last):
  File "C:\Users\danisg\Desktop\Other\Problem.py", line 128, in <module>
    main()
  File "C:\Users\danisg\Desktop\Other\Problem.py", line 124, in main
    t = S.solve()
  File "C:\Users\danisg\Desktop\Other\Problem.py", line 74, in solve
    GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable

是的,你可以有这样的东西:

def eats_a_method(the_method):
    pass

def another_method():
    pass

eats_a_method(another_method)

查看堆栈跟踪:

  GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable

它说
GeneticAlgorithm
是一个
模块
,而不是一个
函数
,从评论来看,问题的根源是:

我做“导入遗传算法”。我不应该这样做格达尼斯

不,那实际上不正确。您所做的是导入模块,而不是导入模块内部的类。您在这里有两个选项-执行一个或另一个:

  • 将导入更改为

    从GeneticAlgorithm导入GeneticAlgorithm

  • 将解算器类更改为使用

    GA=GeneticAlgorithm.GeneticAlgorithm(p,self.fitness,self.bride)


我建议将模块从
GeneticAlgorithm.py
重命名为不太容易混淆的模块(
GeneticAlgorithm.py
),然后使用第一个选项仅从该模块导入类-
来自遗传算法导入遗传算法

请发布实际产生错误的代码。对于初学者:1。缩进已关闭(如果
def
是GeneticAlgorithm类的一部分,则需要缩进)。2.GeneticAlgorithm应该从对象继承。是的,您可以传入函数或方法。“模块”错误意味着您意外地传入了模块,而不是模块中的函数。也许您有一个名为“fred”的模块,其中包含一个名为“fred”的函数,那么您需要传入
fred。fred
现在我们知道问题出在哪里,但不知道问题出在哪里。发布实际错误后,控制台中的堆栈跟踪将
GeneticAlgorithm
定义为一个类,但错误消息称它是一个模块。如果您在计算机上运行的内容与您在此处发布的内容完全不同,则没有人可以调试您的代码。
def eats_a_method(the_method):
    pass

def another_method():
    pass

eats_a_method(another_method)
  GA = GeneticAlgorithm(P, self.fitness, self.breed)
TypeError: 'module' object is not callable