You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python类设置可选参数?象棋游戏棋子移动参数传参问题

解决方案

核心思路

给__init__方法中非必填的方向参数设置默认值,即可实现不传对应参数时自动用默认值填充的效果。你可以根据业务逻辑选择默认值,比如不需要对应方向移动能力的话可以设为0或者None,这里以默认值None为例。

修改后完整代码

class Chess:
    # 非必填参数设置默认值为None,可根据实际需求修改默认值
    def __init__(self, piece, top=None, bottom=None, right=None, left=None, 
                 top_left=None, bottom_left=None, top_right=None, bottom_right=None):
        self.piece = piece
        self.top = top
        self.bottom = bottom
        self.right = right
        self.left = left
        self.top_left = top_left
        self.bottom_left = bottom_left
        self.top_right = top_right
        self.bottom_right = bottom_right

    def make_brick(self):
        # 优化:自动过滤掉值为None的方向,只保留有配置的移动规则
        move_rules = {}
        if self.top is not None:
            move_rules["Top"] = self.top
        if self.bottom is not None:
            move_rules["Bottom"] = self.bottom
        if self.right is not None:
            move_rules["Right"] = self.right
        if self.left is not None:
            move_rules["Left"] = self.left
        if self.top_left is not None:
            move_rules["TopLeft"] = self.top_left
        if self.bottom_left is not None:
            move_rules["BottomLeft"] = self.bottom_left
        if self.top_right is not None:
            move_rules["TopRight"] = self.top_right
        if self.bottom_right is not None:
            move_rules["BottomRight"] = self.bottom_right
        piece_moves = {
            self.piece: move_rules
        }
        return piece_moves

# 实例化棋子,只传需要配置的方向参数即可
farmer = Chess("Farmer", top=1)
print(farmer.make_brick())

运行结果

{'Farmer': {'Top': 1}}

额外优化建议

如果后续要新增更多方向参数,还可以把方向参数用**kwargs接收进一步简化代码,减少__init__的参数长度。


内容的提问来源于stack exchange,提问作者Dolphin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 08:24:04