如何在Python中访问类及方法内部变量(遗传算法世代计数器示例)
问题原因
你的世代计数器counter是GuessText类的实例属性,之前你创建GuessText实例后直接传给了GeneticAlgorithm没有保存引用,导致外部无法访问这个属性,最后打印阶段引用的counter是不存在的全局变量,会直接报错。
修复方法
只需要把GuessText的实例提前赋值给变量保存,算法运行结束后直接访问该实例的counter属性即可,仅需修改if __name__ == "__main__"末尾的执行代码:
if __name__ == "__main__": # 前面的GuessText类定义无需修改 # 先保存GuessText实例 ga_task = GuessText("""The smartest and fastest Pixel yet. Google Tensor: Our first custom-built processor. The first processor designed by Google and made for Pixel, Tensor makes the new Pixel phones our most powerful yet. The most advanced Pixel Camera ever. Capture brilliant color and vivid detail with Pixels best-in-class computational photography and new pro-level lenses.""") # 传入实例运行遗传算法 GeneticAlgorithm(ga_task).run() print('done:') # 直接访问实例存储的counter值 print("%d generations" % ga_task.counter)
原理说明
GuessText的__init__方法初始化了self.counter = 0,每次调用check_stop判断终止条件时该值都会自增,数值全程保存在你创建的ga_task实例中,只要实例没有被销毁,随时可以通过实例名.counter获取当前累计的世代数。
内容的提问来源于stack exchange,提问作者Raz0rmaddnes
相关产品推荐
相关产品推荐

