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

如何为Python Cards类实现points(self)方法以返回卡牌及点数?

解决方案

先修正原代码的核心问题,再给出完整可运行的实现:

核心问题说明

  • 原代码直接使用self[0]会报错,因为self是Cards类的实例对象,并非字符串,需要先在类的初始化方法中存储卡牌字符串(比如self.card),再通过self.card[0]提取牌面等级。
  • 原逻辑仅判断了"2",未覆盖"2"-"6"的所有目标牌面。

完整Cards类实现

class Cards:
    # 类属性:定义合法牌面、花色和点数池
    Card_rank = ["2", "3", "4", "5", "6", "Q", "J", "K", "7", "A"] 
    Cardsuit = ["H", "C", "S", "D"] 
    points2 = ["0", "2", "3", "4", "10", "11"]

    def __init__(self, card_str):
        # 初始化时验证卡牌合法性
        if len(card_str) != 2 or card_str[0] not in self.Card_rank or card_str[1] not in self.Cardsuit:
            raise ValueError("无效卡牌格式,需为'等级+花色',例如'2H'")
        self.card = card_str

    def points(self):
        # 提取卡牌的等级部分
        rank = self.card[0]
        # 处理2-6的情况:对应points2的0点
        if rank in {"2", "3", "4", "5", "6"}:
            result = f"{self.card} Card points is {self.points2[0]}"
            print(result)
            return (self.card, self.points2[0])  # 若需要返回值而非仅打印,保留此行
        # 处理其他等级的点数映射(按需补充)
        else:
            # 建立等级到points2的映射关系
            rank_point_map = {
                "7": self.points2[1],
                "A": self.points2[2],
                "K": self.points2[3],
                "J": self.points2[4],
                "Q": self.points2[5]
            }
            result = f"{self.card} Card points is {rank_point_map[rank]}"
            print(result)
            return (self.card, rank_point_map[rank])

使用示例

# 创建卡牌实例
card1 = Cards("2C")
card2 = Cards("QD")
# 调用points方法
card1.points()  # 输出:2C Card points is 0
card2.points()  # 输出:QD Card points is 11

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 08:20:30