
本文介绍如何为 python 实例创建真正动态、实例专属的只读属性,使其支持 ide/repl 的 tab 补全(仅显示该实例实际拥有的键),同时禁止修改、保持字典后端只读语义。
本文介绍如何为 python 实例创建真正动态、实例专属的只读属性,使其支持 ide/repl 的 tab 补全(仅显示该实例实际拥有的键),同时禁止修改、保持字典后端只读语义。
在 Python 中,若希望对象支持 obj.attr 语法访问内部字典中的值,并让这些属性表现为实例级、只读、可补全,单纯使用描述符(descriptor)会因类属性共享导致跨实例污染(如 a1.x 和 a2.y 的属性混杂出现在同一补全列表中)。而仅靠 __getattr__ 又无法被 dir() 或 Tab 补全识别。真正的解决方案在于协同重写三个特殊方法:__getattr__、__setattr__ 和关键的 __dir__,并辅以 types.MappingProxyType 保障只读契约。
以下是推荐实现:
from types import MappingProxyType
from typing import Any, List, Dict, Union
class DynamicReadOnly:
def __init__(self, keys: List[str], values: List[Any]) -> None:
# 使用普通 dict 存储,便于初始化和运行时访问
self._d: Dict[str, Any] = dict(zip(keys, values))
@property
def d(self) -> MappingProxyType:
"""公开只读视图,防止外部意外修改底层字典"""
return MappingProxyType(self._d)
def __getattr__(self, name: str) -> Any:
"""当常规属性查找失败时,尝试从 _d 中获取"""
try:
return self._d[name]
except KeyError:
raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'")
def __setattr__(self, name: str, value: Any) -> None:
"""禁止对已存在于 _d 中的键赋值;允许设置其他新属性(如 _cache)"""
# 避免在 __init__ 中触发此逻辑(此时 _d 尚未设置)
if hasattr(self, '_d') and name in self._d:
raise TypeError(f"Cannot assign to read-only attribute '{name}'")
super().__setattr__(name, value)
def __dir__(self) -> List[str]:
"""定制 dir() 输出,使 Tab 补全仅显示当前实例有效的动态属性"""
# 获取父类 dir 结果(含方法、内置属性等)
attrs = super().__dir__()
# 移除内部字典名 _d(避免暴露实现细节)
if '_d' in attrs:
attrs.remove('_d')
# 动态注入当前实例所有键作为可补全属性
attrs.extend(self._d.keys())
# 去重并排序,提升可读性(非必需但推荐)
return sorted(set(attrs))✅ 使用示例:
让 macOS 自动化像说话一样简单 —— 用代码控制你的 Mac,无需学习 AppleScript 系统要求 macOS 14+ (Sonoma) Python 3.9+ 需要开启:辅助功能 + 屏幕录制权限
a = DynamicReadOnly(['x', 'y'], [10, 'hello'])
b = DynamicReadOnly(['z', 'count'], [3.14, 42])
print(a.x) # → 10
print(b.z) # → 3.14
print(a.d) # → mappingproxy({'x': 10, 'y': 'hello'})
# ✅ 补全友好:在 IPython/Jupyter 中输入 `a.` + Tab,仅显示 x、y、d 等;
# 输入 `b.` + Tab,仅显示 z、count、d —— 完全隔离!
# ❌ 写保护生效:
# a.x = 99 # → TypeError: Cannot assign to read-only attribute 'x'
# b.count = 0 # → TypeError: Cannot assign to read-only attribute 'count'
# ✅ 允许新增非 _d 键的属性(如缓存、配置):
a._cache = {'computed': True} # ✅ 合法⚠️ 注意事项:
立即学习“Python免费学习笔记(深入)”;
-
__dir__是补全功能的核心——多数 IDE(VS Code、PyCharm)和交互式环境(IPython、Jupyter)依赖它生成建议列表; -
MappingProxyType不仅提供只读视图,还防止obj.d.clear()或obj.d.update(...)等误操作; -
__setattr__中通过hasattr(self, '_d')判断是否已完成初始化,避免__init__过程中对_d自身赋值被拦截; - 若需完全禁止新增任意属性(即实现“封闭实例”),可添加
__slots__ = ('_d',),但会牺牲灵活性(无法动态加_cache等辅助属性)。
这种模式正是 pandas DataFrame 列访问(如 df.column_name)背后的原理之一:不预定义属性,而靠 __getattr__ + __dir__ 实现轻量、精准、可扩展的动态接口。

















