如何让Club类的__str__方法输出不含Wood/Iron/Putter的指定格式?
解决方案
当然可以实现,以下是几种不同思路的可行方案:
方法1:字符串分割快速处理
直接对ClubHead子类的__str__结果做分割,去掉开头的类型前缀:
class Club: def __init__(self, label, head): self._label = label.upper() self._head = head def __str__(self): # 从第一个逗号位置截断,保留后续内容 head_content = str(self._head).split(',', 1)[1] return f'{self._label},{head_content}'
这种方式无需修改现有ClubHead子类代码,但依赖子类__str__的固定格式(前缀+逗号+属性内容),如果后续子类输出格式变化可能失效。
方法2:新增专用方法(更健壮)
在ClubHead基类中定义一个返回核心属性的方法,子类重写该方法补充自身属性,从根源上分离类型标识和属性内容:
from abc import ABC class ClubHead(ABC): def __str__(self): return f'{self._loft:.1f},{self._weight}' # 新增方法:返回不带类型前缀的属性字符串 def get_core_attrs(self): return f'{self._loft:.1f},{self._weight}' class WoodHead(ClubHead): def __str__(self): return f'Wood,{super().__str__()},{self._size}' def get_core_attrs(self): return f'{super().get_core_attrs()},{self._size}' class IronHead(ClubHead): def __str__(self): return f'Iron,{super().__str__()},{self._material}' def get_core_attrs(self): return f'{super().get_core_attrs()},{self._material}' class PutterHead(ClubHead): def __str__(self): return f'Putter,{super().__str__()},{self._style}' def get_core_attrs(self): return f'{super().get_core_attrs()},{self._style}' class Club: def __init__(self, label, head): self._label = label.upper() self._head = head def __str__(self): return f'{self._label},{self._head.get_core_attrs()}'
这种方式遵循封装原则,不依赖字符串拼接格式,后续子类维护时只需同步更新get_core_attrs方法即可,健壮性更强。
方法3:直接访问属性(耦合度较高)
如果允许直接访问ClubHead的私有属性,可以直接拼接所需字段(不推荐长期使用,破坏封装):
class Club: def __init__(self, label, head): self._label = label.upper() self._head = head def __str__(self): base_attrs = f'{self._head._loft:.1f},{self._head._weight}' # 根据头部类型补充额外属性 if isinstance(self._head, WoodHead): extra = f',{self._head._size}' elif isinstance(self._head, IronHead): extra = f',{self._head._material}' elif isinstance(self._head, PutterHead): extra = f',{self._head._style}' else: extra = '' return f'{self._label},{base_attrs}{extra}'
内容的提问来源于stack exchange,提问作者schizetia
相关产品推荐
相关产品推荐

