2d Array of (Individual) Objects in Python 2.7.3

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • AClap
    New Member
    • Dec 2012
    • 2

    2d Array of (Individual) Objects in Python 2.7.3

    Hi,

    I would like to create a 2d array of objects ex. 50 by 40 cells containing a Tile object each, but I can't figure out how to declare this structure. Built-in array structure doesn't seem to be able to contain custom data, but I might be wrong.

    I'd really appreciate if someone could help me out!

    Thanks,
    AClap
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    If you are familiar with Python classes, it is straightforward to setup a custom array.

    A very basic example:
    Code:
    class Array(object):
        def __init__(self, rows, cols):
            self.rows = rows
            self.cols = cols
            # initialize array and fill with zeroes
            self.data = [[0 for _ in range(cols)] for _ in range(rows)]
        def __iter__(self):
            for row in self.data:
                yield row
        def __repr__(self):
            return 'Array(%d, %d)' % (self.rows, self.cols)
    What do you mean by "Tile object"?

    Comment

    • AClap
      New Member
      • Dec 2012
      • 2

      #3
      By Tile object I mean instances of the Tile Class, through I'll have to take the time to understand your code, it does work the way I wanted it to. Thank You.

      Comment

      Working...