[英]Child object 'str' object is not callable, unable to rectify from other similar posts
I am attempting to create a child object from random variables within a list.我正在尝试从列表中的随机变量创建一个子对象。 I have included all code that I have tried.我已经包含了我尝试过的所有代码。 Googling the errors brings up many posts and solutions, none of which seem to be exactly parallel enough for me to utilize.谷歌搜索错误带来了许多帖子和解决方案,但似乎没有一个完全平行,足以让我使用。 Thanks for your time and consideration.感谢您的时间和考虑。
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
You have quotes ("") around Skeleton
and Dragon
- making them strings您在Skeleton
和Dragon
周围有引号 ("") - 使它们成为字符串
Remove the quotes to reference the class rather than the string删除引号以引用类而不是字符串
Note: this will not fix the error in this line: monster = random.choice(MONSTERS(*monster_stats))
注意:这不会修复此行中的错误: monster = random.choice(MONSTERS(*monster_stats))
To fix this, use: monster = random.choice(MONSTERS)(*monster_stats)
要解决此问题,请使用: monster = random.choice(MONSTERS)(*monster_stats)
Try this:尝试这个:
import random
class Monster:
name = None
def __init__(self, level):
self.level = level
class Dragon(Monster):
name = "Dragon"
def attack(self):
print("The Dragon breathes fire!")
class Skeleton(Monster):
name = "Skeleton"
def attack(self):
print("The Skeleton strikes with its sword!")
MONSTERS = [Skeleton, Dragon]
monster_cls = random.choice(MONSTERS)
monster_level = 1
monster_stats = [monster_level] # maybe you have other stats too
monster = monster_cls(*monster_stats)
The main fix is to have a list of classes instead of strings: MONSTERS = [Skeleton, Dragon]
主要解决方法是使用类列表而不是字符串: MONSTERS = [Skeleton, Dragon]
A couple of other suggestions:其他几个建议:
name
is the type of the monster (and not an individual name like Smaug) then it doesn't need to be an arg to __init__
如果name
是怪物的类型(而不是像 Smaug 这样的个人名称),那么它不需要是__init__
的 argbreathe_fire
else if monster is a Skeleton then strike
"如果所有怪物都有一个共同的攻击方法,你可能会发现其余代码更容易,否则当你进行战斗时,你将不得不有很多代码,例如“如果怪物是龙,那么就breathe_fire
,否则如果怪物是骷髅然后strike
”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.