【问题标题】:Mention outer classes in an inner class在内部类中提及外部类
【发布时间】:2022-11-02 17:22:26
【问题描述】:

如何从该类内部的类访问继承列表?

嗨,我一直在尝试在 pygame 中创建一个带有棋子的棋盘,并希望通过一个“Board”类和其中一个包含所有国际象棋特定代码的“Chess”类来保持事物整洁。

在国际象棋课中,我有一个函数(测试),它为国际象棋“网格”上的每个方格分配一块。

如何在“测试”功能中使用板子的 self.grid 列表?

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

我希望能够做到这一点:

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

【问题讨论】:

标签: python


【解决方案1】:

您不能直接从嵌套内部类中的外部类访问属性。对于您的用例,您可以考虑将网格作为参数传递给您的方法调用

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

    
    class Chess:
        ...
        
        def test(self, grid):
            for square in grid:
                square.type = Board.Chess.order[grid.index(square)]

【讨论】:

    猜你喜欢
    • 2013-04-26
    • 2023-01-24
    • 2011-03-10
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-21
    相关资源
    最近更新 更多