Skip to content
Advertisement

Here is the problem discription: print(snake_array[0].x) AttributeError: ‘list’ object has no attribute ‘x’ . I cannot find the mistake

class Test:
    def __init__(self, x, y, dir):
        self.x = x
        self.y = y
        self.dir = dir


def snake_init(snake_array):
    snake_array.append([Test(300, 300, "RIGHT")])
    snake_array.append([Test(301, 300, "RIGHT")])
    snake_array.append([Test(302, 300, "RIGHT")])
    print(snake_array[0].x)


snake_array = []
snake_init(snake_array)

Advertisement

Answer

The problem is that you are appending lists to snake_array, not Test objects. This is what you’re appending: [Test(300, 300, "RIGHT")]. Notice that the brackets make it a list. All you need to do is remove the extra brackets. Like this:

class Test:
    def __init__(self, x, y, dir):
        self.x = x
        self.y = y
        self.dir = dir


def snake_init(snake_array):
    snake_array.append(Test(300, 300, "RIGHT"))
    snake_array.append(Test(301, 300, "RIGHT"))
    snake_array.append(Test(302, 300, "RIGHT"))
    print(snake_array[0].x)


snake_array = []
snake_init(snake_array)
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement