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

如何设计Python类:直接引用返回值,点语法访问子属性

解决方案:让_DTYPE继承str并扩展属性

要实现直接访问h.DTYPE返回原始字符串(如<f8>),同时保留h.DTYPE.character这类子属性访问的需求,最简洁的方式是让_DTYPE类继承Python内置的str类型,同时在实例化时解析并添加自定义属性。

实现代码

class _DTYPE(str):
    def __new__(cls, dtype_str):
        # 因为str是不可变类型,必须通过__new__创建实例并初始化
        instance = super().__new__(cls, dtype_str)
        
        # 解析DTYPE的子结构(可根据实际格式调整逻辑)
        # 处理字节序:首字符为<小端、>大端,默认=主机字节序
        if dtype_str[0] in ('<', '>'):
            instance.endian = dtype_str[0]
            type_part = dtype_str[1:]
        else:
            instance.endian = '='
            type_part = dtype_str
        
        # 解析类型字符和字节宽度
        instance.character = type_part[0]
        instance.width = int(type_part[1:])
        
        return instance

class Header:
    def __init__(self, dtype_str, nmemb, nfile):
        self.DTYPE = _DTYPE(dtype_str)
        self.NMEMB = nmemb
        self.NFILE = nfile

效果验证

# 初始化Header实例
h = Header('<f8', 10, 5)

# 直接赋值变量得到原始字符串
raw_dtype = h.DTYPE
print(raw_dtype)  # 输出: <f8
print(type(raw_dtype))  # 输出: <class '__main__._DTYPE'>(但完全兼容str操作)

# 访问子属性
print(h.DTYPE.endian)      # 输出: <
print(h.DTYPE.character)   # 输出: f
print(h.DTYPE.width)       # 输出: 8

# 作为str使用的场景完全正常
print(raw_dtype + '_modified')  # 输出: <f8_modified

原理说明

  1. 继承str的特性:_DTYPE继承自str,因此它的实例本质就是字符串对象——赋值给变量时直接返回字符串内容,支持所有str的内置操作(拼接、切片等),无需依赖__str__/__repr__仅在print时生效的限制。
  2. 添加自定义属性:通过__new__方法(因为str是不可变类型,不能用__init__修改实例),在创建字符串实例的同时,解析并附加endian、character、width等子属性,实现属性访问需求。

扩展提示

如果你的DTYPE格式有更多变体(比如无字节序、多字符类型标识等),只需在_DTYPE的__new__方法中调整解析逻辑即可,完全不影响其作为字符串的核心特性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 16:55:13