比较 Python 中的闭包

发布于 01-13 20:59 字数 603 浏览 3 评论 0原文

我的目标是比较两个有界闭包,并检查它们是否以相同的输入参数 len 为界,

def foo(len: int):
    def foob():
        return len
    return foob

a = foo(1)
b = foo(1)
print(a == b)

输出为 False。 但是,当我使用以下命令检查相等性时,

print(a.__closure__ == b.__closure__)

当输入参数 len 不同时,输出似乎为 True 和 False (正如我希望它工作的那样)。当我遍历此类函数闭包签名的大字典时,问题就出现了,其中检查的是 __eq__ 而不是 __closure__。有什么办法可以解决这个问题吗?

更新:问题不够清晰。 如果我要做这样的事情:

a_dict[foo(1)] = 0x12

即使 foo(1) 存在于字典中,它也会为 foo(1) 创建一个新的闭包对象,因为它使用 __eq__ 方法进行检查。

My goal is to compare two bounded closures and check if they are bounded with the same input argument len

def foo(len: int):
    def foob():
        return len
    return foob

a = foo(1)
b = foo(1)
print(a == b)

The output is False.
But when I check for equality using the following,

print(a.__closure__ == b.__closure__)

the output appears to be True and False when the input argument len is different (just as I want it to work). The problem comes when I am traversing through a large dictionary of such function closure signature where __eq__ is checked for instead of __closure__. Is there any way to get around this?

UPDATE: There was a lack of clarity in the problem.
If I were to do something like this:

a_dict[foo(1)] = 0x12

It would create a new closure object for foo(1) even if foo(1) were present in the dictionary as it checks using __eq__ method.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文