简体   繁体   English

访问类实例位于其中的数组的类方法

[英]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: 例如,我可以:

  • Write a method in Tile that returns the instance of Tile before it in the list. 在Tile中编写一个方法,该方法返回列表中位于其之前的Tile实例。
  • I could write a method from within Tile that returns all the other Tile instances in the list it's in. 我可以在Tile中编写一个方法,该方法返回其所在列表中的所有其他Tile实例。

These would work no matter what list the class instance was in. Is this possible to do in python? 无论类实例所在的列表是什么,它们都将起作用。这可以在python中完成吗?

EDIT 编辑


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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM