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 define a variable in Python that points to or is a reference to a list member JeffDelmas 4 157 Feb-28-2021, 10:38 PM
Last Post: JeffDelmas
  apendng to a list within a class gr3yali3n 4 183 Feb-16-2021, 06:30 AM
Last Post: buran
  Create variable and list dynamically quest_ 12 350 Jan-26-2021, 07:14 PM
Last Post: quest_
  How to append multiple <class 'str'> into a single List ahmedwaqas92 2 244 Jan-07-2021, 08:17 AM
Last Post: ahmedwaqas92
  How to create new line '/n' at each delimiter in a string? MikeAW2010 3 305 Dec-15-2020, 05:21 PM
Last Post: snippsat
  How to create a linked list and call it? loves 12 601 Nov-22-2020, 03:50 PM
Last Post: loves
  Passing List of Objects in Command Line Python usman 7 632 Sep-27-2020, 03:45 PM
Last Post: ndc85430
  Class objects Python_User 12 943 Aug-27-2020, 08:02 PM
Last Post: Python_User
  How to define a function to create a resorted list? sparkt 6 573 Aug-08-2020, 04:10 PM
Last Post: sparkt
  printing class properties from numpy.ndarrays of objects pjfarley3 2 432 Jun-08-2020, 05:30 AM
Last Post: pjfarley3

Forum Jump:

User Panel Messages

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