[英]Class method that accesses the array the class instance is inside
Using python 2.7- I have a file, main.py
, that does something like 使用python 2.7-我有一个文件
main.py
,它的功能类似于
from tile import Tile
l = [Tile(), Tile(), Tile()]
where tile.py
contains the Tile class. 其中
tile.py
包含Tile类。 I need the Tile class to access l
in the main file. 我需要Tile类访问主文件中的
l
。 For example, I could: 例如,我可以:
These would work no matter what list the class instance was in. Is this possible to do in python? 无论类实例所在的列表是什么,它们都将起作用。这可以在python中完成吗?
Exactly what I'm trying to do: I have a Tile
class. 正是我想要做的:我有一个
Tile
类。 world
is a 2D array, a list of lists. world
是一个2D数组,一个列表列表。 The lists have Tile
class objects. 列表具有
Tile
类对象。 I'm trying to implement a method of Tile
, returnNeighbors()
, that returns the tiles to the top, bottom, left and right in the array. 我正在尝试实现
Tile
方法, returnNeighbors()
,该方法将瓦片返回到数组的顶部,底部,左侧和右侧。
There is no way you can access the list from inside the class unless you pass it as a function. 除非您将其作为函数传递,否则无法从类内部访问列表。 You could try that, but as others have mentioned, this generally means that the design is bad and you should rethink it.
您可以尝试一下,但是正如其他人提到的那样,这通常意味着设计不好,您应该重新考虑它。
<inside the class Tile>
# function for the first use-case in your question
def your_function(self, your_list):
return your_list[your_list.index(self) -1]
# second use-case
def your_other_function(self, your_list):
temp = your_list
temp.remove(self)
return temp
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.