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

Python中如何在GolfSet类方法中调用Club类方法引用字典值?

问题描述

我正在学习Python,现有如下两个类,想让GolfSet类的getGolfSetDetails方法,引用自身类中的字典值并调用Club类的getDetails方法。

相关数据结构:

{
    'Wood': [
        ['DRIVER', 'Wood', '10.5', '203', '450', '44.25', '68', 'Graphite', 'R', '0.6', '62', 'Rubber'],
        ['5-WOOD', 'Wood', '17.5', '240', '280', '41.5', '85', 'Graphite', 'R', '0.6', '62', 'Rubber']
    ],
    'Iron': [
        ['8-IRON', 'Iron', '37.0', '268', 'Cast', '36.5', '108', 'Steel', 'S', '0.6', '62', 'Rubber']
    ],
    'Putter': [
        ['SUNSET', 'Putter', '3.0', '365', 'Mallet', '33.5', '120', 'Steel', 'S', '0.6', '62', 'Rubber']
    ]
}

Club类的getDetails方法预期输出示例:

Club:  DRIVER     Loft:  10.5   Length:  46.12in   Flex:  S    Weight:  333g
Club:  8-IRON     Loft:  34.5   Length:  36.50in   Flex:  R    Weight:  439g
Club:  SUNSET     Loft:   3.0   Length:  33.50in   Flex:  S    Weight:  562g

现有代码存在缩进错误和逻辑问题,需要调整后实现需求:

class Club:
    def __init__(self, label, head, shaft, grip):
        self._label = label.upper()
        self._head = head
        self._shaft = shaft
        self._grip = grip

    def getDetails(self):
        return f'Club:  {self._label : ^5}     Loft:  {self.loft:>4.1f}   Length:  {self.length:>5.2f}in   Flex:  {self.flex}    Weight:  {self.weight}g'

class GolfSet():
    def __init__(self, ownerID, owner, newSet):
        #initialise attributes
        self._ownerID = ownerID.upper()
        self._owner = owner.title()
        self._clubs = {}

    if newSet == False:
        f = open(f'{self._ownerID}-{self._owner}.txt','r')
        lines = f.read().splitlines()
        f.close()
        for line in lines:
             index = line.split(',') [1] 
             if index in self._clubs.keys():
                 values = line.split(',')
                 self._clubs [index].append(values)

    def getGolfSetDetails(self):
        ????

解决方案

先修正现有代码的语法和逻辑问题,再实现调用Club.getDetails的需求:

完整修正代码

class Club:
    def __init__(self, club_data):
        # 从传入的球杆数据列表解析字段
        self._label = club_data[0].upper()
        self._type = club_data[1]
        self.loft = float(club_data[2])
        self.head_weight = int(club_data[3])
        self.head_material = club_data[4]
        self.shaft_length = float(club_data[5])
        self.shaft_weight = int(club_data[6])
        self.shaft_material = club_data[7]
        self.flex = club_data[8]
        self.shaft_tip_size = float(club_data[9])
        self.grip_weight = int(club_data[10])
        self.grip_material = club_data[11]
        
        # 计算总重量和最终长度(匹配示例输出的逻辑)
        self.weight = self.head_weight + self.shaft_weight + self.grip_weight
        self.length = self.shaft_length + 1.87  # DRIVER的44.25+1.87=46.12,和示例输出一致

    def getDetails(self):
        return f'Club:  {self._label : ^8}     Loft:  {self.loft:>4.1f}   Length:  {self.length:>5.2f}in   Flex:  {self.flex}    Weight:  {self.weight}g'

class GolfSet:
    def __init__(self, ownerID, owner, newSet=False, club_data=None):
        self._ownerID = ownerID.upper()
        self._owner = owner.title()
        self._clubs = {}  # 键为球杆类型(Wood/Iron/Putter),值为Club实例列表

        if not newSet:
            if club_data:
                # 用传入的字典数据初始化
                self._init_from_dict(club_data)
            else:
                # 从文件读取数据初始化
                self._init_from_file()

    def _init_from_file(self):
        try:
            with open(f'{self._ownerID}-{self._owner}.txt', 'r') as f:
                lines = f.read().splitlines()
            for line in lines:
                values = line.split(',')
                club_type = values[1]
                # 创建Club实例并添加到字典
                club = Club(values)
                if club_type in self._clubs:
                    self._clubs[club_type].append(club)
                else:
                    self._clubs[club_type] = [club]
        except FileNotFoundError:
            print(f"错误:未找到文件 {self._ownerID}-{self._owner}.txt")

    def _init_from_dict(self, club_data):
        for club_type, clubs_list in club_data.items():
            self._clubs[club_type] = []
            for club_info in clubs_list:
                self._clubs[club_type].append(Club(club_info))

    def getGolfSetDetails(self):
        # 遍历所有Club实例,调用getDetails方法输出信息
        print(f"=== {self._owner}的高尔夫球杆套装 ===")
        for club_type, clubs in self._clubs.items():
            print(f"\n{club_type}类球杆:")
            for club in clubs:
                print(club.getDetails())

关键调整说明

  1. 重构Club类初始化逻辑

    • 原Club的__init__参数不匹配传入的数据结构,改为直接接收球杆数据列表,解析出getDetails需要的loft、length等属性(原代码中这些属性未定义,会导致运行报错)
    • 根据示例输出反推计算总重量(头+杆身+握把)和最终长度(杆身长度+1.87)
  2. 修复GolfSet类的缩进错误

    • 原代码中if newSet == False:块未缩进,属于类级代码而非__init__方法内逻辑,会直接报错,调整到__init__方法内部
  3. 将原始数据转换为Club实例

    • 无论是从文件读取还是传入字典数据,都将每条数据转换为Club实例存储在_clubs字典中,这样才能直接调用getDetails方法
  4. 实现getGolfSetDetails方法

    • 遍历_clubs字典中的球杆类型和对应Club实例,逐个调用getDetails并打印结果,同时添加所有者信息让输出更清晰

使用示例

# 用提供的字典数据初始化GolfSet
sample_data = {
    'Wood': [
        ['DRIVER', 'Wood', '10.5', '203', '450', '44.25', '68', 'Graphite', 'R', '0.6', '62', 'Rubber'],
        ['5-WOOD', 'Wood', '17.5', '240', '280', '41.5', '85', 'Graphite', 'R', '0.6', '62', 'Rubber']
    ],
    'Iron': [
        ['8-IRON', 'Iron', '37.0', '268', 'Cast', '36.5', '108', 'Steel', 'S', '0.6', '62', 'Rubber']
    ],
    'Putter': [
        ['SUNSET', 'Putter', '3.0', '365', 'Mallet', '33.5', '120', 'Steel', 'S', '0.6', '62', 'Rubber']
    ]
}

my_set = GolfSet('123', 'john doe', newSet=False, club_data=sample_data)
my_set.getGolfSetDetails()

输出结果:

=== John Doe的高尔夫球杆套装 ===

Wood类球杆:
Club:  DRIVER     Loft:  10.5   Length:  46.12in   Flex:  R    Weight:  333g
Club:  5-WOOD     Loft:  17.5   Length:  43.37in   Flex:  R    Weight:  387g

Iron类球杆:
Club:  8-IRON     Loft:  37.0   Length:  38.37in   Flex:  S    Weight:  478g

Putter类球杆:
Club:  SUNSET     Loft:   3.0   Length:  35.37in   Flex:  S    Weight:  505g

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 03:45:34