如何创建一个在每次读取访问时评估函数的对象?

问题描述 投票:0回答:1

我想要一个对象来存储一个内部函数,该函数在每次读取访问时进行评估,因此这些读取访问返回的值在某种程度上是动态的。

示例:

import time


class MyWrapper:
    def __init__(self, function):
        self.function = function
    
    # Example 
    def __read_access__(self):
        return self.function()


def test_function():
    return (time.time() % 2 ) > 0


test = MyWrapper(test_function)

# Tested multiple times because it's kind of random
print(f"{test=}")
print(f"{test=}")
print(f"{test=}")

# Should be working with 'is' comparator with True, False and None
print(f"{test is True}")
print(f"{test is True}")
print(f"{test is True}")

结果示例:

test=True
test=False
test=True

False
False
True

例如,它可以用于以对变量用户透明的方式将变量绑定到文件的内容,甚至数据库行。

@property
工作得很好,但据我所知,它仅适用于具有
instance.value
访问权限的类方法,但不能直接在变量上使用。

python wrapper
1个回答
-1
投票

Python 中的 is 运算符用于测试两个变量/对象是否引用内存中的同一个对象。它比较两个对象的身份,而不是它们的值

这很像说

id(obj1) == id(obj2)
© www.soinside.com 2019 - 2024. All rights reserved.