python 链式调用 合并 __setattr__ __getattribute__ in nested object()
使用场景:bpy.types.Scene与bpy.context.scene部分功能重叠。
def Get(obj, attr: str | Sequence[str], root=False):
"""injected recursive getattr, could pollute objects on chain in whole session"""
IS_STR = isinstance(attr, str)
if IS_STR and attr.startswith("__") and attr != "__getattribute__":
return object.__getattribute__(obj, attr)
E: Exception | None = None
objs = obj if root else (obj,)
for i, o in enumerate(objs):
at = attr if IS_STR else attr[i]
try:
obj_inject = getattr(o, at)
setattr(obj_inject, "__getattribute__", Get)
return obj_inject
except AttributeError as e:
if " object attribute '__getattribute__' is read-only" in str(e):
return obj_inject
E = e
if E:
raise E
else:
raise
class A:
att = True
class B:
at = False
if __name__ == "__main__":
at = Get([A, B], "at", root=True)
print("😄", at)
等价于:
A.at # no attr named 'at'
B.at

浙公网安备 33010602011771号