简体   繁体   English

如何传递可选功能参数

[英]How to pass optional function parameter

I am currently learning python and tried to implement chess. 我目前正在学习python并尝试实现国际象棋。 (I've already done this in multiple different languages) (我已经用多种不同的语言完成了此操作)

class Board:

    def __init__(self):
        self._reset()

    def _reset(self, func=Board.default_layout):
        self.values = [[0 for x in range(8)] for i in range(8)]
        self.currentPlayer = 1
        func(self.values)

    @staticmethod
    def default_layout(values):
        pass


if __name__ == "__main__":
    b = Board()

The idea of the reset method is to reset the board. 重置方法的想法是重置板。 The pieces on it will be removed and a function will be called that places the pieces on the board in the initial layout. 上面的零件将被删除,并会调用一个函数,以初始布局将这些零件放置在板上。

There are chess versions, where there are different starting layouts. 有国际象棋版本,其中有不同的开始布局。 Therefor I wanted to make it an optional parameter with the default method: default_layout(self) 因此,我想使用默认方法使其成为可选参数: default_layout(self)

However this code does not compile and I would like to know where my problem is. 但是,此代码无法编译,我想知道我的问题在哪里。

I get the error message: 我收到错误消息:

NameError: name 'default_layout' is not defined 

Your def _reset(self, func=Board.default_layout): is being evaluated as part of the definition of Board , so Board.default_layout is not defined yet. 您的def _reset(self, func=Board.default_layout):被评估为Board定义的一部分,因此Board.default_layout尚未定义。

You could make default_layout an ordinary function instead of a static method. 您可以将default_layout普通函数,而不是静态方法。 It needs to be defined before you use it. 使用前需要先定义它。

def default_layout(values):
    ... whatever

class Board:
    ...
    def _reset(self, func=default_layout):
        ...

Or, if it must be a static method, don't try and reference it inside the function declaration. 或者,如果它必须是静态方法,请不要尝试在函数声明中引用它。 You can reference it inside the function body , because the body isn't executed until the function is actually called. 您可以在函数主体内部引用它,因为直到实际调用函数才执行主体。

    def _reset(self, func=None):
        if func is None:
            func = Board.default_layout

As an alternative to @khelwood's answer, you can also use a lambda function instead if you prefer to keep default_layout a static method of the Board class. 作为@khelwood答案的替代方法,如果您希望保留default_layoutBoard类的静态方法,则也可以使用lambda函数。

Change: 更改:

def _reset(self, func=Board.default_layout):

to

def _reset(self, func=lambda values: Board.default_layout(values)):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM