如何在python中有效地命名大量实例?

  • 本文关键字:实例 有效地 python python oop
  • 更新时间 :
  • 英文 :


我正在用python做OOP;我有一个叫做mesh_grid的类。我需要创建很多对象。在某些情况下,我认为可能需要多达一百万个对象,甚至更多。现在我想实例化它,并以某种自动方式为实例命名,如下面的代码所示。

问题是,使用vars()['some string']是最有效(计算密集度较低)的方法吗?有没有其他更好的方法?

class mesh_grid:
num_mg = 0
def __init__(self):
self.coord = ()             # Coordinates
self.sol_conc = 0           # Solute concentration (physical quantity)
mesh_grid.num_mg += 1
num_nodes = 20
for num in range(1,num_nodes+1):
vars()['mg'+str(num)] = mesh_grid()

我猜你有兴趣创建类型mesh_grid的很多对象,并希望访问/显示它在一个合理的和有效的是以后。下面是一个基于列表的解决方案。

class mesh_grid:
num_mg = 0
def __init__(self):
self.coord = ()             # Coordinates
self.sol_conc = 0           # Solute concentration (physical quantity)
mesh_grid.num_mg += 1
nodes = []
for num in range(20):
nodes.append(mesh_grid())

通过

可以实现大量访问(例如输出)
for node in nodes:
print(node.coord, node.col_conc)

如果mesh_grid.num_mg的目的是获取节点的数量,那么这可以通过集合list有效地完成,在上面所示的情况下。

下面是一个没有这个类成员的例子,我还更改了一些名称:节点类为mesh_node,集合为mesh_grid,因为在这种情况下表示网格(仍然由列表实现)。我还允许通过将初始化器传递给__init__来指定成员值:

稠密网格

import random # simulate concentrations by random values
class mesh_node:
def __init__(self, coord = (), sol_conc = 0):
self.coord = coord
self.sol_conc = sol_conc
width = 3
height = 3
mesh_grid = []
for i in range(width*height):
mesh_grid.append(mesh_node((i % width, i // width), random.randint(1, 6)))

for node in mesh_grid:
print(node.coord, node.sol_conc)

下面是一个输出示例:

(0, 0) 2
(1, 0) 3
(2, 0) 5
(0, 1) 1
(1, 1) 3
(2, 1) 1
(0, 2) 6
(1, 2) 6
(2, 2) 4

稀疏网格

如果您正在实现稀疏网格,最好切换到dict容器。这里使用coord作为键,sol_conc作为值,只存储现有节点:

import random
class MeshGrid:
nodes = dict()
def set_node(self, coord, sol_conc):
self.nodes[coord] = sol_conc
def __str__(self):
return 'n'.join([f'{k} {v}' for k, v in self.nodes.items()])

width = 100
height = 100
grid = MeshGrid()
for i in range(width*height):
# simulate that about 1/1000 nodes exist:
if random.random() > 0.999:
grid.set_node((i % width, i // width), random.randint(1, 6))

print(grid)

以下是100 x 100网格的示例输出,节点位于10,000个潜在位置中的11个:

(5, 11) 2
(17, 27) 6
(95, 29) 6
(49, 41) 4
(96, 45) 3
(87, 47) 1
(17, 52) 6
(23, 61) 5
(54, 68) 6
(73, 79) 1
(11, 93) 3

最新更新