在 Python 中,构造函数可以接受另一个类的方法作为参数吗?
我听说你可以做这样的事情,但这个例子不起作用(目前,我得到一个“模块”对象不可调用错误):
class GeneticAlgorithm ():
def __init__(self, population, fitness, breed, retain = .3, weak_retain = .15 ) :
self.fitness = 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 main():
S = Solver(fitness, breed, 35)
print(S.solve())
if __name__ == '__main__':
main()