如何获取Python对象的非默认属性?当前最优实现方法
获取对象自定义属性的最优实现方法
首先得明确你要获取的是实例对象的自定义属性还是类对象的自定义属性,两种场景的最优实现略有区别:
1. 获取实例对象的自定义属性
如果你的MyObject是实例,直接通过列表推导式过滤掉默认的双下划线包裹的特殊属性就行:
# 过滤所有以双下划线开头并结尾的属性(覆盖绝大多数默认特殊属性) custom_attrs = [attr for attr in vars(my_instance).keys() if not (attr.startswith('__') and attr.endswith('__'))]
要是你想精确排除指定的默认属性(比如不想误删自己定义的__my_custom_attr__这类属性),可以手动指定要排除的集合:
default_attrs = {'__module__', '__dict__', '__weakref__', '__doc__'} custom_attrs = [attr for attr in vars(my_instance).keys() if attr not in default_attrs]
2. 获取类对象的自定义属性
如果MyObject是类本身,vars()返回的是类的命名空间,包含很多默认特殊属性。可以结合dir()和过滤逻辑,或者用inspect模块更灵活地筛选:
方法一:纯列表推导式
custom_class_attrs = [ attr for attr in dir(MyClass) if not (attr.startswith('__') and attr.endswith('__')) # 可选:如果要排除类中的方法,加上下面这行 # and not callable(getattr(MyClass, attr)) ]
方法二:用inspect模块(更清晰,适合复杂场景)
import inspect custom_class_attrs = [ name for name, _ in inspect.getmembers(MyClass) if not (name.startswith('__') and name.endswith('__')) ]
注意:如果需要区分属性是类自身定义的还是继承来的,可以在推导式里加上
hasattr(MyClass, attr) and attr in MyClass.__dict__的判断,确保只拿到类自身的属性。
内容的提问来源于stack exchange,提问作者david
相关产品推荐
相关产品推荐

