您能否仅使用对象的变量地址访问对象的属性?

2024-04-25 01:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

如何更有效地遍历链接数组

global matrix

#initalize matrix as a 2d array 50 by 50

class cell:
    def __init___(self, x, y):
        self.i = x
        self.j = y
        self.array = []

#each matrix index has a cell object
for i in range(0, 50):
    for j in range(0, 50):
        matrix[i][j] = cell(i, j)

#each cell has an array of other cells
matrix[0][0].array = [matrix[0][1], matrix[1][0], matrix[1][1]]



#prints out a cell from an array of another
print("Example 1: ", matrix[0][0].array[0])

>>> Example 1: <__main__.cell object at 0x000001F4426D5F40>



#to link cells the 'dot' operator is used repeatedly
matrix[0][0].array[0].array = [matrix[0][0], matrix[2][1], matrix[1][2]]



#to access other cells down the chain the 'dot' operator is repeatedly
print("Example 2: ", matrix[0][0].array[0].array[0])

>>> Example 2: <__main__.cell object at 0x000001F4428EB0A0>

问题是如何在不重复使用“点”操作符的情况下遍历数组