遗传算法中如何获取对象实际值而非内存地址?
解决Python打印Chromosome对象显示内存地址的问题
我看到你在运行遗传算法代码时,打印染色体对象得到的是内存地址而非实际基因值,比如输出里的 <__main__.Chromosome instance at 0x7f7c81a41050>,这是Python的默认行为,咱们来快速搞定它:
问题根源
Python中,当你直接打印一个自定义类的实例时,默认会调用该类的__str__(或__repr__)方法,而这两个方法的默认实现就是返回对象的类名和内存地址。所以要让打印显示实际值,咱们得给Chromosome类自定义这两个方法之一。
解决方案
在你的Chromosome类中添加__str__方法,让它返回染色体的实际基因内容。假设你的Chromosome类里有一个存储基因的属性(比如self.genes,可能是列表或字符串类型),示例代码如下:
class Chromosome: # 你的其他代码(比如初始化、计算适应度的方法) def __init__(self): # 示例初始化,根据你的实际代码调整 self.genes = [] self.fitness = 0 def __str__(self): # 如果genes是列表,转成字符串输出;如果本身是字符串直接返回即可 return ''.join(str(gene) for gene in self.genes)
为什么这能解决问题?
当你在_print_population方法中打印x(也就是Chromosome实例)时,Python会自动调用我们自定义的__str__方法,返回基因的字符串表示,而不再是默认的内存地址。
验证修改后的效果
修改后,你的打印输出会变成类似这样:
Chromosome # 0 : 1100101 | Fitness: 10
附上你提供的原始代码方便参考:
@staticmethod def _select_tournament_population(pop): tournament_pop = Population(0) i = 0 while i < TOURNAMENT_SELECTION_SIZE: tournament_pop.get_chromosomes().append(pop.get_chromosomes()[random.randrange(0, POPULATION_SIZE)]) i += 1 tournament_pop.get_chromosomes().sort(key=lambda x: x.get_fitness(), reverse=True) return tournament_pop def _print_population(self, pop, gen_number): print("\n------------------------------------------------") print("Generation #", gen_number, "| Fittest chromosome fitness:", pop.get_chromosomes()[0].get_fitness()) print("Target Chromosome:", TARGET_CHROMOSOME) print("------------------------------------------------") i = 0 for x in pop.get_chromosomes(): print("Chromosome #", i, " :", x, "| Fitness: ", x.get_fitness()) i += 1
内容的提问来源于stack exchange,提问作者Bipin Mishra
相关产品推荐
相关产品推荐

