May-13-2023, 09:05 PM
list comprehensions have their own scope, and they can only access variables defined within their own scope or in the outer scope.
In this case, x and y are defined as class variables,so they are not directly accessible within the list comprehension.
To fix this issue can make instance variables instead of class variables.
In this case, x and y are defined as class variables,so they are not directly accessible within the list comprehension.
To fix this issue can make instance variables instead of class variables.
class MyClass: def __init__(self, x=8, y=9): self.x = x self.y = y self.grid = [[0 for _ in range(self.x)] for _ in range(self.y)] my_instance = MyClass(3, 4) print(my_instance.grid)
Output:[[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]
If call it like MyClass()
it will make default 8, 9 grid.