对象内的实例化对象形式的访问列表

时间:2020-07-05 09:28:34

标签: python class object

我想使用Python 3对象类内的方法访问实例化对象的列表。 我认为我无法将整个列表提供给该对象,因为它将包含自身。

具体:如何从类cells[]中访问cell?还是这是错误的思考方式?最终目标是轻松编程像cell.moveUp()这样的单元格行为-所有单元格都连接到8个邻居。

我可能缺少一些东西,可能是因为我在python /编程方面没有太多经验。

#!/usr/bin/env python3
import random


class cell:
    """ cell for celluar automata """

    def __init__(self, n=0, nghbrs=[], a=0.00, b=0.00, c=0.00):
        self.n = n #id
        self.nghbrs = nghbrs #list of connected neighbors
        self.a = a  #a value of the cell 
        self.b = b
        self.c = c

    def growUp(self):
        if self.a > .7:  # if cell is "bright"
            cells[self.nghbrs[7]].a = self.a  # update cell above (nghbrs[7] = cell above )


def main():
    iterations = 4
    links = initLinks()  # 150 random links [link0, link2, ... , link7]*150
    val1 = initval()  # 150 random values

    cells = [cell(nghbrs[0], nghbrs[1], val1[nghbrs[0]])for nghbrs in enumerate(
        links)]  # create cell objects, store them in cells and init. neigbours , a

    for i in range(iterations):  # celluar automata loop
        for c in cells:
            c.growUp()


def initLinks(): #for stackoverflow; in real use the cells are arranged in a grid
    nghbrs = []
    for i in range(150):
        links = []
        for j in range(8):
            links.append(random.randrange(0, 150))
        nghbrs.append(links)
    return nghbrs


def initval():
    vals = []
    for i in range(150):
        vals.append(random.random())
    return vals


if __name__ == "__main__":
    main()

按原样运行,无法在方法growUp()中访问单元格:

NameError: name 'cells' is not defined

2 个答案:

答案 0 :(得分:0)

您可以创建一个CellsList类(list的子类),该类具有调用的方法来获取新单元格。

class CellsList(list):
    def add_cell(self, *args, **kwargs):
        """
        make a cell, append it to the list, and also return it
        """
        cell = Cell(cells_list=self, *args, **kwargs)
        self.append(cell)
        return cell

然后在单元格本身中(我已将类重命名为Cell,并且按照常规的大写约定,我在实例变量中使用了cell作为属性),您具有属性cells_list您在其中存储对单元格列表的反向引用。 (我还修复了nghbrs的初始化,以避免默认值中的可变对象。)

class Cell:
    """ cell for celluar automata """

    def __init__(self, n=0, nghbrs=None, a=0.00, b=0.00, c=0.00, cells_list=None):
        self.n = n #id
        self.nghbrs = (nghbrs if nghbrs is not None else []) #list of connected neighbors
        self.a = a  #a value of the cell 
        self.b = b
        self.c = c
        self.cells_list = cells_list
        
    def growUp(self):
        if self.a > .7:  # if cell is "bright"
            self.cells_list[self.nghbrs[7]].a = self.a  # update cell above (nghbrs[7] = cell above )

然后在main内,您可以更改直接实例化Cell(或称为cell)的当前代码(与cells = ...的行)来代替使​​用cells.add_cell

    cells = CellsList()
    for nghbrs in enumerate(links):
        cells.add_cell(nghbrs[0], nghbrs[1], val1[nghbrs[0]])

在这里,我们实际上并没有使用add_cell返回的值,但是无论如何我们都会返回它。

注意:该方法允许您根据需要维护单元格的多个独立列表,因为它不依赖任何类变量来保存列表-所有内容都保存在实例变量中。因此,例如,您的主程序可以通过多次实例化CellsList并调用相关add_cell实例的CellsList方法来创建多个区域,从而对每个区域进行建模,从而对每个区域进行建模一个新的单元格。

答案 1 :(得分:0)

您可以通过使单元格列出类的静态变量来跟踪cell()的实例,可以从该类的所有实例中轻松访问这些变量。

[{'title': 'XXX#1092', 'views': '1983228'}, {'title': 'xxEP#1091', 'views': '2559581'}, {'title': 'xx', 'views': '183545'}, {'title': ' Official Music Video', 'views': '439534'}]
>>>