当我在Zombie类中调用render()方法时,我想将Zombie对象的实例添加到ZombieList.list中。当我尝试执行此操作时,它会显示
类
list
的未解析属性引用ZombieList
。
我应该尝试另一种方式吗?
class ZombieList:
def __init__(self):
self.list = []
for zombie in self.list:
ds.blit(zombie.image, (1000, random.randint(10, 790)))
class Zombie(object):
def __init__(self):
self.attack = 3
self.speed = 5
self.health = 30
self.image = pygame.image.load("Assets/green zombie.png")
self.zombieList = []
def render(self):
ZombieList.list.append(self)
答案 0 :(得分:1)
您必须创建一个ZombieList
对象,可以在其中添加Zombie
对象。
您可以将Class Objects添加到类Zombie
中:
class Zombie(object):
zombies = ZombieList()
def __init__(self):
self.attack = 3
self.speed = 5
self.health = 30
self.image = pygame.image.load("Assets/green zombie.png")
def render(self):
Zombie.zombies.list.append(self)
答案 1 :(得分:0)
list
中没有属性ZombieList
。仅通过以下方式创建了ZombieList
后self.zombie_list = ZombieList()
,您将能够通过self.zombie_list.list
使用您的列表。
尽管如此,即使如此,我仍然想这可能不是您要针对的设计:我想象您不希望每个ZombieList
都使用Zombie
。相反,初始化Zombie
对象的人可能也应该负责维护ZombieList
实例。
您还将遇到其他问题。例如,循环
self.list = []
for zombie in self.list:
ds.blit(zombie.image, (1000, random.randint(10, 790)))
永远不会有任何作用,因为执行该代码时self.list
始终为空(因为您已在上一行中将其定义为空)。
答案 2 :(得分:0)
您不能追加到课程列表。您需要附加到类的 instance 。例如:
class ZombieList:
def __init__(self):
self.list = []
for zombie in self.list:
ds.blit(zombie.image, (1000, random.randint(10, 790)))
my_zombie_list = ZombieList() # create an instance
class Zombie(object):
def __init__(self):
self.attack = 3
self.speed = 5
self.health = 30
self.image = pygame.image.load("Assets/green zombie.png")
self.zombieList = []
def render(self):
my_zombie_list.list.append(self) # refer to the previously created instance