我正在创建数千个对象,这需要几秒钟(可以理解)。我想确定的是,作为一个最近从另一种不太突出的语言转过来的人,这是一种有效的方法来创建这么多对象还是浪费资源?
class Library:
def __init__(self, i):
self.exe = str(i['exe'])
self.path = str(i['path'])
self.name = str(i['name'])
self.longpath = str(i['longpath'])
# exampled output times 3k
# longpath: 'C:\program files\Steam\common\\Half-Life\hlds.exe'
# exe: 'hlds.exe'
# name: 'Half-Life Dedicated Server'
#
#starts here from main file, passing a list of dictionaries
def constructor(gameLib):
# create library objects,
# using a list to keep track
lib = []
x = 0
for i in gameLib:
lib.append(Library(i))
print(lib[x].exe)
x = x + 1
return lib
def callThings(lib):
print(lib[3].path)
pass
除了代码的效率之外,还必须考虑它的可读性。另外,print语句通常开销很大。所以我建议这样重构
class Library:
def __init__(self, game_lib):
self.exe = str(game_lib['exe'])
self.path = str(game_lib['path'])
self.name = str(game_lib['name'])
self.longpath = str(game_lib['longpath'])
def constructor(game_lib):
return [Library(lib) for lib in game_lib]
def call_things(lib):
print(lib[3].path)