【问题标题】:AttributeError: 'World' object has no attribute 'draw'AttributeError:“世界”对象没有属性“绘制”
【发布时间】:2021-06-07 04:47:05
【问题描述】:

所以我正在开发一款有趣的平台游戏。我尝试运行代码,但出现此错误:

'World' 对象没有属性'draw'

这是我的世界级:

class World():
def __init__(self, data):
    self.tile_list = []

    #load images
    def draw():
    

        dirt_img = pygame.image.load('assets/images/dirt.png')
        grass_img = pygame.image.load('assets/images/grass.png')
        row_count = 0
        for row in data:
            col_count = 0
            for tile in row:
                if tile == 1:
                    img = pygame.transform.scale(dirt_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count * tile_size
                    img_rect.y = row_count * tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                if tile == 2:
                    img = pygame.transform.scale(grass_img, (tile_size, tile_size))
                    img_rect = img.get_rect()
                    img_rect.x = col_count * tile_size
                    img_rect.y = row_count * tile_size
                    tile = (img, img_rect)
                    self.tile_list.append(tile)
                col_count += 1
            row_count += 1

然后我在这里调用 world.draw 属性:

world = World(world_data)
world.draw()

另外,如果您想知道,world_data 只是一个包含一堆数字的列表,这些数字告诉代码世界应该是什么样子。

请帮帮我,我一直在努力解决这个问题。

【问题讨论】:

  • 你的缩进是否正确?
  • 好吧,如果此处的缩进与您的代码匹配,则该类的结构不正确,因此它认为 draw 方法是 __init__ 函数的一部分,而不是 World 的一部分完全上课

标签: python


【解决方案1】:

问题在于你的缩进。您需要以某种方式更改它们,以便 draw 方法成为 World 类的一部分。

class World:
    def __init__(self, data):
        self.tile_list = []
        self.data = data

    #load images
    def draw(self):
        pass

当你这样做的时候,你需要给这个方法一个self参数,因为一个类中的每个方法都必须有它,除非它是一个static method

我认为您正在尝试做某事,但您做错了。您在__init__ 方法中放入的任何代码都将在您创建该类的实例时执行;但是您想稍后调用draw 方法。最好的方法是按照我所说的定义draw 方法,然后需要将data 参数保存为实例变量,并且在需要使用它时,将其用作self.data

for row in self.data:

【讨论】:

    猜你喜欢
    • 2018-06-29
    • 2012-12-01
    • 2021-04-19
    • 2021-11-22
    • 1970-01-01
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 2016-03-27
    相关资源
    最近更新 更多