Home > Enterprise >  Here is the problem discription: print(snake_array[0].x) AttributeError: 'list' object has
Here is the problem discription: print(snake_array[0].x) AttributeError: 'list' object has

Time:09-27

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)

CodePudding user response:

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)
  • Related