"""演示 __getattr__ 懒加载缓存,以及 __getattribute__ 拦截所有访问。""" from __future__ import annotations from typing import Any class Lazy: def __init__(self) -> None: self.loaded = False def __getattr__(self, name: str) -> Any: if name == "payload": self.loaded = True value = {"value": 42} self.__dict__["payload"] = value return value raise AttributeError(name) class Loud: value = 7 def __init__(self) -> None: object.__setattr__(self, "seen", []) def __getattribute__(self, name: str) -> Any: if name == "seen": return object.__getattribute__(self, name) object.__getattribute__(self, "seen").append(name) return object.__getattribute__(self, name) def main() -> None: lazy = Lazy() print(f"before: {lazy.loaded}") print(f"first: {lazy.payload}") print(f"cached: {'payload' in lazy.__dict__}") print(f"after: {lazy.loaded}") try: _ = lazy.missing except AttributeError as exc: print(f"missing: {exc}") loud = Loud() print(f"value: {loud.value}") print(f"seen: {loud.seen}") if __name__ == "__main__": main()