0

How can I access an inheritance's list from an class inside of that class?

Hi I've been trying to create a chess board in pygame with pieces and wanted to keep things neat by having a "Board" class and in it, a "Chess" class that would contain all the chess specific code.

In the chess class I have a function (test) that assigns each square on the chess "grid" a piece.

How can I in the "test" function use the board's self.grid list?

class Board:
    def __init__(self, size):
        self.size = size
        self.grid = []
        for y in range(self.size):
            for x in range(self.size):
                self.grid.append(Square(x, y, self.size))

    
    class Chess:
        order = ['r', 'n', 'b', 'q', 'k', 'b', 'n', 'r',
                 'p', 'p', 'p', 'p', 'p', 'p', 'p', 'p', 
                 '-', '-', '-', '-', '-', '-', '-', '-', 
                 '-', '-', '-', '-', '-', '-', '-', '-', 
                 '-', '-', '-', '-', '-', '-', '-', '-', 
                 '-', '-', '-', '-', '-', '-', '-', '-', 
                 'P', 'P', 'P', 'P', 'P', 'P', 'P', 'P',
                 'R', 'N', 'B', 'Q', 'K', 'B', 'N', 'R']
        
        def test(self):
            for square in self.grid:
                square.type = Board.Chess.order[self.grid.index(square)]

I want to be able to do this:

board = Board(8) board.Chess.test()

PogoSpin
  • 23
  • 3
  • you can use `"Board"` – user70 Nov 02 '22 at 09:17
  • 2
    Does this answer your question? [How to access outer class from an inner class?](https://stackoverflow.com/questions/2024566/how-to-access-outer-class-from-an-inner-class) – user70 Nov 02 '22 at 09:19
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Nov 02 '22 at 09:38

1 Answers1

0

You cannot directly access attributes from the outer class in your nested inner class. For your use-case, you might consider passing the grid to your method call as an argument

class Board:
    def __init__(self, size):
        ...

    
    class Chess:
        ...
        
        def test(self, grid):
            for square in grid:
                square.type = Board.Chess.order[grid.index(square)]
Abirbhav G.
  • 369
  • 3
  • 14