How to create and define in one line a 2D list of class objects in Python - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: How to create and define in one line a 2D list of class objects in Python (/thread-29023.html) |
How to create and define in one line a 2D list of class objects in Python - T2ioTD - Aug-14-2020 I am attempting to create a hex based strategy game, and I am using Pygame for the first time. Also, while I have many years of experience in coding, this is the first time I use classes and objects. The Hex class needs to be defined with x and y, and when I try to create a MAP list made of hex objects, I do not know how to define in one line the instances: Class Hex(): def __init__(self, x, y): self.x = x self.y = y hex_map = [[Hex(i,j) for j in range(1,10)] for i in range(1,10)] Python generates an error because the variable i was not declared when Hex(i,j) is introduced... Is there a way to do it? RE: How to create and define in one line a 2D list of class objects in Python - Yoriz - Aug-14-2020 See commented corrected code below class Hex: # should be lower cass class def __init__(self, x, y): # indent 4 spaces not 2 self.x = x # indent another 4 spaces inside of the def self.y = y # indent another 4 spaces inside of the def hex_map = [[Hex(i, j) for j in range(1, 10)] for i in range(1, 10)] # should not be indent here |