Python Forum
How to create and define in one line a 2D list of class objects in Python
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to create and define in one line a 2D list of class objects in Python
#1
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?
Reply
#2
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
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to read module/class from list of strings? popular_dog 1 422 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  How can I access objects or widgets from one class in another class? Konstantin23 3 929 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Delete strings from a list to create a new only number list Dvdscot 8 1,466 May-01-2023, 09:06 PM
Last Post: deanhystad
  Create Excel Line Chart Programmatically dee 3 1,143 Dec-30-2022, 08:44 PM
Last Post: dee
  [split] why can't i create a list of numbers (ints) with random.randrange() astral_travel 7 1,428 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Creating list of lists, with objects from lists sgrinderud 7 1,561 Oct-01-2022, 07:15 PM
Last Post: Skaperen
Question Keyword to build list from list of objects? pfdjhfuys 3 1,499 Aug-06-2022, 11:39 PM
Last Post: Pedroski55
  How to store the resulting Doc objects into a list named A xinyulon 1 1,852 Mar-08-2022, 11:49 PM
Last Post: bowlofred
  Python code to read second line from CSV files and create a master CSV file sh1704 1 2,353 Feb-13-2022, 07:13 PM
Last Post: menator01
  Cannot convert the series to <class 'int'> when trying to create new dataframe column Mark17 3 8,387 Jan-20-2022, 05:15 PM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020