简体   繁体   中英

How to pass optional function parameter

I am currently learning python and tried to implement chess. (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)

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.

You could make default_layout an ordinary function instead of a static method. 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.

Change:

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

to

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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