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

Question:

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)
Asked By: Hubert Pastusiak

||

Answers:

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)
Answered By: Michael M.
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.