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


Messages In This Thread
How to create and define in one line a 2D list of class objects in Python - by T2ioTD - Aug-14-2020, 12:25 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  how to get qualified objects in a list Azdaghost 5 826 Apr-22-2025, 06:03 PM
Last Post: Azdaghost
  Create a new subclass in a Python extension based on an existing class voidtrance 6 1,694 Mar-25-2025, 06:37 PM
Last Post: voidtrance
  Entry field random pull from list, each return own line Bear1981 6 1,022 Feb-25-2025, 06:09 AM
Last Post: Pedroski55
  How does this code create a class? Pedroski55 6 2,342 Apr-21-2024, 06:15 AM
Last Post: Gribouillis
  How to read module/class from list of strings? popular_dog 1 1,428 Oct-04-2023, 03:08 PM
Last Post: deanhystad
  How can I access objects or widgets from one class in another class? Konstantin23 3 2,906 Aug-05-2023, 08:13 PM
Last Post: Konstantin23
  Delete strings from a list to create a new only number list Dvdscot 8 3,635 May-01-2023, 09:06 PM
Last Post: deanhystad
  Create Excel Line Chart Programmatically dee 3 2,201 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 3,103 Oct-23-2022, 11:13 PM
Last Post: Pedroski55
  Creating list of lists, with objects from lists sgrinderud 7 3,369 Oct-01-2022, 07:15 PM
Last Post: Skaperen

Forum Jump:

User Panel Messages

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