分配一个仅等于其自身的值

发布于 2024-08-21 15:52:00 字数 805 浏览 5 评论 0原文

我希望分配给一个变量(“常量”),该值将允许该变量仅在 is==True代码> 与自身的比较。

我想避免分配任意值,例如 int 或其他类型,以防我选择的值与其他值发生冲突。

我正在考虑生成一个类的实例,该实例使用 CPython 的 id 的唯一性() 值可能支持的任何比较中的值。

来自这里

If no __cmp__(), __eq__()  or __ne__()  operation is defined, class instances are compared by object identity (“address”).

建议:

MY_CONSTANT = object()

只会永远< /em> 在与 CPython 实现上的 MY_CONSTANT 进行比较时返回 true,如果 MY_CONSTANT 以某种方式被垃圾收集,并且在比较期间在其位置分配了其他内容(我假设这个可能永远不会发生)。

I wish to assign to a variable (a "constant"), a value that will allow that variable to only ever return True in is and == comparisons against itself.

I want to avoid assigning an arbitary value such as an int or some other type on the off chance that the value I choose clashes with some other.

I'm considering generating an instance of a class that uses the uniqueness of CPython's id() values in any comparisons the value might support.

From here:

If no __cmp__(), __eq__()  or __ne__()  operation is defined, class instances are compared by object identity (“address”).

Would suggest that:

MY_CONSTANT = object()

Will only ever return true in a comparison with MY_CONSTANT on a CPython implementation if MY_CONSTANT was somehow garbage collected, and something else allocated in it's place during the comparison (I would assume this is probably never going to happen).

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

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

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

心安伴我暖 2024-08-28 15:52:00

只要 MY_CONSTANT 停留在范围内,它引用的对象就不能被垃圾收集。
您确实应该始终使用is进行比较,因为==的行为可以被覆盖

As long as MY_CONSTANT stays in scope the object it references can not be garbage collected.
You really should always use is for comparison, as the behaviour of == can be overridden

对你的占有欲 2024-08-28 15:52:00

是的。这是定义唯一常量的好方法。当然,无论你将其与什么对象进行比较,被定义为等于一切的风险都是最小的,但如果每个人都玩得相当好,这应该可行。另外,垃圾收集问题也不会成为问题,因为如果发生这种情况,您的常量已经消失,并且无法与具有相同 id 的新对象进行比较。

Yes. This is a good way to define unique constants. There is of course, the minimal risk of whatever object you are comparing it to being defined as equal to everything, but if everyone is playing reasonably nicely, this should work. Also, the garbage collection issue won't be a problem, because if that should ever happen, your constant has already gone away, and isn't around to compare equal to the new object with the same id.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文