Python中如何非显式访问并打印类实例属性(规避__dict__)
没问题,咱们来搞定这两个需求,同时避开你提到的不规范的__dict__访问方式——确实,直接碰对象的内部字典不是个好习惯,属于依赖实现细节的做法,咱们用更优雅规范的方法来实现。
核心思路
要实现“遍历实例属性+动态访问属性”,关键靠两个工具:
- 用
dir()或inspect模块获取属性名列表(过滤掉特殊属性和方法) - 用
getattr()函数动态获取属性值(不用显式写self.prop1这种硬编码的方式)
方案一:基础版(dir() + getattr())
这是最常用的写法,足够应对大多数普通场景:
class MyClass: def __init__(self): self.prop1 = None self.prop2 = 10 def print_properties(self): # 遍历所有可访问的属性名 for attr_name in dir(self): # 过滤掉双下划线开头的内置特殊属性(比如__init__、__class__) if not attr_name.startswith('__'): attr_value = getattr(self, attr_name) # 排除方法,只保留实例属性 if not callable(attr_value): print(f"{attr_name}: {attr_value}") example_a = MyClass() example_a.print_properties()
运行后会输出你期望的结果:
prop1: None prop2: 10
方案二:严谨版(inspect模块)
如果你的类继承了父类,或者有更多复杂的成员,用inspect模块能更精准地筛选出当前实例的属性,避免误把继承来的方法或属性算进来:
import inspect class MyClass: def __init__(self): self.prop1 = None self.prop2 = 10 def print_properties(self): # 筛选出非方法/非函数的成员,再过滤特殊属性 for attr_name, attr_value in inspect.getmembers(self, lambda x: not inspect.ismethod(x) and not inspect.isfunction(x)): if not attr_name.startswith('__'): print(f"{attr_name}: {attr_value}") example_a = MyClass() example_a.print_properties()
为什么不用__dict__?
你提到的旧回答里用object.__dict__.keys()的方式,问题在于__dict__是Python对象的内部存储结构,有些类(比如用__slots__定义的类)甚至没有__dict__,直接访问它会导致代码兼容性问题,而且不符合“面向对象封装”的原则——我们应该用公开的API来操作对象,而不是直接扒内部实现。
内容的提问来源于stack exchange,提问作者HSchmachty
相关产品推荐
相关产品推荐

