如何创建每次读取访问时都会执行函数的Python对象?
实现动态读取的函数包装对象
我想要一个能存储内部函数的对象,每次对它进行读取访问时都会执行该函数,让返回的值具备动态性。比如可以将变量与文件内容或数据库行绑定,对变量使用者而言完全透明。
@property装饰器虽表现良好,但它仅适用于类实例的instance.value访问方式,无法直接用于普通变量。
示例代码
import time class MyWrapper: def __init__(self, function): self.function = function # 自定义读取逻辑示例 def __read_access__(self): return self.function() def test_function(): return (time.time() % 2 ) > 0 test = MyWrapper(test_function) # 多次测试,结果具有随机性 print(f"{test=}") print(f"{test=}") print(f"{test=}") # 需要支持与True、False、None使用'is'关键字比较 print(f"{test is True}") print(f"{test is True}") print(f"{test is True}")
示例运行结果
test=True test=False test=True False False True
内容的提问来源于stack exchange,提问作者Olivier
相关产品推荐
相关产品推荐

