有没有办法检查测试为相等(==)的Python对象的(不同)内部结构?
昨天我问(“在 Python 2.5 下行为不同的表面上相等的集合列表的情况(我认为……)”)为什么列表 W 构造如下:
r_dim_1_based = range( 1, dim + 1)
set_dim_1_based = set( r_dim_1_based)
def listW_fill_func( val):
if (val == 0):
return set_dim_1_based
else:
return set( [val])
W = [ listW_fill_func( A[cid])
for cid in r_ncells ]
没有按照我的预期运行。特别是,它的行为不像其他列表那样显示与它相等(another_list == W --> True)。
是否有一个实用程序、技巧、内置的东西可以向我展示这些不同的内部结构?可能会产生类似 C 的对象声明,以便我立即看到我在一种情况下处理指针(列表 W)而在其他情况下处理值?
Yesterday I asked ("A case of outwardly equal lists of sets behaving differently under Python 2.5 (I think …)") why list W constructed as follows:
r_dim_1_based = range( 1, dim + 1)
set_dim_1_based = set( r_dim_1_based)
def listW_fill_func( val):
if (val == 0):
return set_dim_1_based
else:
return set( [val])
W = [ listW_fill_func( A[cid])
for cid in r_ncells ]
didn't behave as I expected. In particular, it did not behave like other lists that showed equality with it (another_list == W --> True).
Is there a utility, trick, builtin, whatever that would have shown these differing internal structures to me? Something that would have produced perhaps a C-like declaration of the objects so that I would have seen at once that I was dealing with pointers in one case (list W) and values in the others?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您在每种情况下都处理引用(更类似于指针而不是值)。您当然可以内省对象对您内心内容的引用 - 例如,如果您有一个列表并想要检查是否有任何项目是相同的引用,
请注意我们在这里讨论的是引用 - 因此,两个相同的引用
None
或对int
值17
的两个相同引用也会触发相同的警报。当然,您可以继续反省以删除这种情况,例如,如果您认为对同一不可变对象的多个引用很好,则在第一遍中从列表中消除不可变对象 - 例如:但我会质疑投资回报率如此深刻的反省策略!
You're dealing with references in each case (more similar to pointers than to values). You can surely introspect your objects' references to your heart's contents -- for example, if you have a list and want to check if any items are identical references,
DO note that we're talking about references here -- so, two identical references to
None
, or two identical references to theint
value17
, would also trigger the same alarm. Of course you can keep introspecting to remove that case, eliminating immutables from the list in a first pass, for example, if you think that multiple references to the same immutable are fine -- e.g.:but I would question the return-on-investment of such a deep introspection strategy!