Python随机创建子类实例报'str' object is not callable错误
问题描述
尝试基于列表内的随机变量创建Monster类的子类实例,已附上所有测试过的代码。检索过该报错相关的诸多帖子与解决方案,均不适配当前使用场景,在此求助。
测试代码
import random class Monster: def __init__(self, name, level): self.name = name self.level = level class Dragon(Monster): def breathe_fire(self): print("The Dragon breathes fire!") class Skeleton(Monster): def strikes(self): print("The Skeleton strikes with its sword!") MONSTERS = ["Skeleton", "Dragon"] monster_type = random.choice(MONSTERS) monster_level = 1 monster_stats = [monster_type, monster_level] print(monster_stats) # create object from child class and pass stats #monster = random.choice(MONSTERS(*monster_stats)) <--'list' object is not callable #monster = Dragon(*monster_stats) # <-- works, but is useless for my purposes #monster = monster_type(*monster_stats) <--- 'str' object is not callable
三种实例化写法的测试结果
- 执行
monster = random.choice(MONSTERS(*monster_stats))时报错:'list' object is not callable - 执行
monster = Dragon(*monster_stats)可正常运行,但无法实现随机选择怪物类型的需求,不符合预期目标 - 执行
monster = monster_type(*monster_stats)时报错:'str' object is not callable
报错原因与修复方案
报错核心原因
当前定义的MONSTERS列表中存储的是类名字符串,不是类本身的引用:
- 第一种写法将
MONSTERS列表作为可调用对象传参,本质是试图调用列表,触发列表不可调用的报错 - 第三种写法中随机得到的
monster_type是字符串类型,试图将字符串作为类执行实例化操作,触发字符串不可调用的报错
修复方案
直接将MONSTERS列表中的字符串替换为实际的类引用即可,不需要存储类名字符串,同时修正参数传递逻辑(不要将选中的类本身作为name参数传入构造方法):
import random class Monster: def __init__(self, name, level): self.name = name self.level = level class Dragon(Monster): def breathe_fire(self): print("The Dragon breathes fire!") class Skeleton(Monster): def strikes(self): print("The Skeleton strikes with its sword!") # 列表直接存储类对象,而非类名字符串 MONSTERS = [Skeleton, Dragon] # 随机选中的结果直接是可实例化的类 monster_class = random.choice(MONSTERS) monster_level = 1 # 实例化时传名称字符串(这里直接用类名作为怪物名)和等级 monster = monster_class(name=monster_class.__name__, level=monster_level) # 测试调用子类专属方法 if isinstance(monster, Dragon): monster.breathe_fire() if isinstance(monster, Skeleton): monster.strikes()
内容的提问来源于stack exchange,提问作者misfit138
相关产品推荐
相关产品推荐

