Python 对象感知数组中的情况吗?
Python 中有没有办法让对象'知道'它的数组元素 id 是什么?即数组中的6,而对象本身打印出自己的数组元素编号,所以'0,1,2,3,4,5'
Is there a way in Python for an object to 'know' what its array element id is? I.e 6 in an array, and the object itself prints out its own array element number, so '0,1,2,3,4,5'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
不。该对象可能同时位于所有对象和多个对象内,因此除非您告诉它,否则它无法知道。
No. The object could be inside everything and multiple objects at the same time, so it can't know unless you tell it.
一句话,不...
In a word, no...
只是迂腐地说:一般来说,不......
但从技术上讲,某些(特定)对象是可能的,这些对象是某些数组的一部分,可以“知道它们的位置”......
从技术上讲,“o”是一个对象......并且是一个数组(s.arr)...并且“知道”它的位置...
Just to be pedantic: in general, no...
but technically it is possible for some (specific) objects, which are part of some arrays to "know their position"...
...technically 'o' is an object...and part of an array (s.arr)...and "knows" it's position...
除非你告诉它,否则不会,而告诉它会导致非常烦人的耦合和/或责任分离问题。您真正想要做什么?
Not unless you tell it, and telling it leads to very annoying coupling and/or separation of responsibility problems. What are you really trying to do?
不,但您可以使用内置的“enumerate”同时迭代索引和元素:
No, but you can use the 'enumerate' builtin to iterate over the index and the element at the same time:
如果对象知道它所属的列表,它可以通过执行
the_list.index(self)
来查找。否则,不行。If the object knows the list it is part of, it could find out by doing
the_list.index(self)
. Otherwise, no.