[英]Child object 'str' object is not callable, unable to rectify from other similar posts
我正在嘗試從列表中的隨機變量創建一個子對象。 我已經包含了我嘗試過的所有代碼。 谷歌搜索錯誤帶來了許多帖子和解決方案,但似乎沒有一個完全平行,足以讓我使用。 感謝您的時間和考慮。
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
您在Skeleton
和Dragon
周圍有引號 ("") - 使它們成為字符串
刪除引號以引用類而不是字符串
注意:這不會修復此行中的錯誤: monster = random.choice(MONSTERS(*monster_stats))
要解決此問題,請使用: monster = random.choice(MONSTERS)(*monster_stats)
嘗試這個:
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)
主要解決方法是使用類列表而不是字符串: MONSTERS = [Skeleton, Dragon]
其他幾個建議:
name
是怪物的類型(而不是像 Smaug 這樣的個人名稱),那么它不需要是__init__
的 argbreathe_fire
,否則如果怪物是骷髏然后strike
”
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.