分配一个仅等于其自身的值
我希望分配给一个变量(“常量”),该值将允许该变量仅在 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
只要 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是的。这是定义唯一常量的好方法。当然,无论你将其与什么对象进行比较,被定义为等于一切的风险都是最小的,但如果每个人都玩得相当好,这应该可行。另外,垃圾收集问题也不会成为问题,因为如果发生这种情况,您的常量已经消失,并且无法与具有相同 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.