类“ ...”的未解析属性引用“ ...”

时间:2019-03-28 21:11:50

标签: python pygame pycharm

当我在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)

3 个答案:

答案 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。仅通过以下方式创建了ZombieListself.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