Search code examples
pythonobjectrecursioncreation

How to recursively create individually accessible objects


I am fairly new at Python and lack formal training. Everything I have learned has been through books and a few videos I have seen. So while I understand basic concepts, I still have trouble with some things many better coders may take for granted. So I need help with this.

I was working on a chess program, and while creating the pawns, I got to wondering how to create them all with one function but be able to access them separately later to change their individual positions. I can't make a string into a variable, like I hoped.

class Name(object):
    def __init__(self, posx, posy, posz):
        self.pos= (posz, posy, posz)
        box(pos=self.pos)

Then I can just create a bunch with positions from a list, but still access them all as separate objects.


Solution

  • One way to make it easier on yourself is to not have the pieces worry about where they are, instead delegating that to a Board object:

    import string
    
    class Piece(object):
        def __init__(self, type, colour):
            self.type = type
            self.colour = colour
        def __str__(self):
            return 'Piece(%(type)s, %(colour)s)' % self.__dict__
    
    class Board(dict):
        def __init__(self, width, height):
            self.update(
                dict(((x,y), None) 
                    for x in string.ascii_lowercase[:width] # alphabetic axis 
                    for y in xrange(1, height+1)            # numeric axis
                )
            )
    
        def setup(self, position_seq):
            for type, colour, position in position_seq:
                self[position] = Piece(type, colour)
    
    initial_positions = [
        ('rook', 'W', ('a', 1)),
        ('knight', 'W', ('b', 1)),
        ('bishop', 'W', ('c', 1)),
        ('queen', 'W', ('d', 1)),
        ('king', 'W', ('e', 1)),
        ('pawn', 'W', ('a', 2)),
    ]
    
    b = Board( 8,8 )
    b.setup( initial_positions )
    print b['a',1] # returns Piece(rook, W)
    

    The setup method for the Board takes a list of tuples, with each containing the data needed to instantiate a new piece, as well as specifying where it should go on the board. No recursion necessary, just a simple loop passing data into a class.