我正在努力在python中实现以下的最佳方法:
我有一个生成各种形状的模拟。在每次运行模拟代码时,都会生成由新行对象组成的新形状,但这些对象需要在多次运行中保持不变。
每条线由折线编码的字符串描述。每次生成新行时,我都需要验证相同的行是否已存在。如果是的话,我想退回原件,如果没有,我想创建一个新的。
我还需要跟踪所有创建的对象,以便在多次模拟运行结束时,我可以将它们全部返回并将它们发送到数据库。
我的第一种方法是使用itertools.count迭代器作为类变量,并在创建时获取新的id(由于遗留原因,我需要同时保留id和字符串)。
class Line(object):
new_id = itertools.count(start=1).next
lines = []
def __init__(self, coord_string):
self.coord_string = coord_string
self.id = Line.new_id()
Line.lines.append(self)
@staticmethod
def from_coord_string(coord_string):
lines = [l.coord_string for l in Line.lines]
try:
ind = lines.index(path)
return Line.links(ind)
except ValueError:
return Line(coord_string)
我还跟踪类变量中所有创建的对象。这让我可以检查是否已经创建了一个Line,或者稍后可以轻松访问所有这些,即:
all_lines = Line.lines
dump_to_db(all_lines)
使用像这样的类变量有什么缺点?是否有更好或更有效的方法来实现它?
答案 0 :(得分:1)
我会做这样的事情:
from itertools import *
from multiprocessing import Lock
class Line(object):
def __init__(self, ID, coord_string):
self.id = ID
self.coord_string = coord_string
class LineFactory(object):
latestId = 0
idLock = Lock()
def __init__(self):
self.lines = {} # Dict mapping coord_string to Line objects
def make_new_id(self):
with self.idLock:
newId = self.latestId
self.latestId += 1
return newId
def new_line(self, coord_string):
if not coord_string in self.lines:
self.lines[coord_string] = Line(self.make_new_id(), coord_string)
return self.lines[coord_string]
def get_all_lines(self):
return self.lines.values