Skip to main content
 首页 » 编程设计

Python OOP 初始化参数错误

2025年05月04日17arxive

这是我的代码:

class Board: 
    def __init__ (self, boardLength, boardHeight, pieces): 
        self.__boardLength = boardLength 
        self.__boardHeight = boardHeight 
        self.__pieces = pieces 
        self.__snapShots = [] 
        self.__tiles = [] 
        while len(self.__tiles) < (self.__boardHeight*self.__boardLength): 
            self.__tiles.append(0) 
 
board1 = Board(5, 4, 
    [u,I_shape(1,'I'),X_shape(3,5,'U'),T_shape(4,5,'U'),L_shape(3,5,'U')] 
) 

我明白了:

TypeError: __init__() takes exactly 4 arguments (3 given) 

我知道 init 有 4 个参数,但其中一个是 self,我给了它另外三个。谁能告诉我我做错了什么?

请您参考如下方法:

我想你的问题实际上是在 I_shape 中,因为你的其他形状都需要 3 个参数。我运行了它并且运行良好,将不存在的类替换为 None。

此外,值得注意的是,99.9% 的时间都不需要使用名称修饰 (__variable)。如果您想表明它是私有(private)的,请使用单个下划线。