将两个功能合并为一个

huangapple go评论53阅读模式
英文:

Combining two functions in one

问题

import numpy as np

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark_combined(self, main_row, main_col, row=None, col=None, player=None):
        if row is None and col is None and player is None:
            self.block[main_row][main_col] = player
        else:
            self.cells[main_row][main_col][row][col] = player
英文:

How can I combine functions mark_block and mark_cell into single function?

import numpy as np

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark_block(self, main_row, main_col, player):
        self.block[main_row][main_col] = player

    def mark_cell(self, main_row, main_col, row, col, player):
        self.cells[main_row][main_col][row][col] = player

EDIT: Would it also be possible to do it without if statement?

答案1

得分: 1

import numpy as np

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark(self, main_row, main_col, player, row=None, col=None):
        if row is None and col is None:
            self.block[main_row][main_col] = player
        else:
            self.cells[main_row][main_col][row][col] = player
英文:
import numpy as np

class Board:

    def __init__(self):
        self.cells = np.zeros((3, 3, 3, 3))
        self.block = np.zeros((3, 3))

    def mark(self, main_row, main_col, player, row=None, col=None):
        if row is None and col is None:
            self.block[main_row][main_col] = player
        else:
            self.cells[main_row][main_col][row][col] = player
        

huangapple
  • 本文由 发表于 2023年2月17日 23:36:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486314.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定