Home > Net >  Mention outer classes in an inner class
Mention outer classes in an inner class

Time:11-02

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()

CodePudding user response:

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)]
  • Related