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

Python如何仅打印类共享变量?求优雅高效的实现方案

实现方案

你可以借助inspect模块过滤掉类中的方法、私有属性和内置特殊属性,直接提取目标类变量的值,不需要额外定义空类做差集,可读性和扩展性都更强:

import inspect

def printOnlySharedVariablesValues(cls):
    res = set()
    for attr_name, attr_val in cls.__dict__.items():
        # 过滤规则:排除私有属性、函数、方法,只保留自定义公开类变量
        if not attr_name.startswith('_') and not inspect.isfunction(attr_val) and not inspect.ismethod(attr_val):
            res.add(attr_val)
    return res

测试效果

class Dummy(object):
    SHARED_0 = '0'
    SHARED_1 = '1'

print(printOnlySharedVariablesValues(Dummy))
# 输出:{'0', '1'}

优化建议

如果你的自定义类变量有统一的命名规范(比如全部大写),可以在过滤条件里加命名校验,过滤精度更高,也不需要引入inspect模块:

def printOnlySharedVariablesValues(cls):
    return {val for name, val in cls.__dict__.items() if name.isupper() and not name.startswith('_')}

如果需要同时取父类中定义的类变量,只需要额外增加遍历父类__dict__的逻辑即可,比原方案的差集逻辑扩展性好很多。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 11:15:06