我为我正在进行的一些实验室实验的结果定义了一个名为Experiment
的类。这个想法是创建一种数据库:如果我添加一个实验,它将在退出之前被腌制到数据库中,并在启动时重新加载(并添加到类注册表中)。
我的类定义是:
class IterRegistry(type):
def __iter__(cls):
return iter(cls._registry)
class Experiment(metaclass=IterRegistry):
_registry = []
counter = 0
def __init__(self, name, pathprotocol, protocol_struct, pathresult, wallA, wallB, wallC):
hashdat = fn.hashfile(pathresult)
hashpro = fn.hashfile(pathprotocol)
chk = fn.checkhash(hashdat)
if chk:
raise RuntimeError("The same experiment has already been added")
self._registry.append(self)
self.name = name
[...]
而fn.checkhash
是一个检查包含结果的文件的哈希值的函数:
def checkhash(hashdat):
for exp in cl.Experiment:
if exp.hashdat == hashdat:
return exp
return False
这样,如果我添加之前添加的实验,它就不会被覆盖。
是否可以以某种方式返回现有实例(如果已经存在)而不是引发错误? (我知道在 __init__ block 中这是不可能的)
最佳答案
如果您想自定义创建而不是仅仅在新创建的对象中进行初始化,可以使用__new__
:
class Experiment(metaclass=IterRegistry):
_registry = []
counter = 0
def __new__(cls, name, pathprotocol, protocol_struct, pathresult, wallA, wallB, wallC):
hashdat = fn.hashfile(pathresult)
hashpro = fn.hashfile(pathprotocol)
chk = fn.checkhash(hashdat)
if chk: # already added, just return previous instance
return chk
self = object.__new__(cls) # create a new uninitialized instance
self._registry.append(self) # register and initialize it
self.name = name
[...]
return self # return the new registered instance
关于python - 如果已经存在,则返回类实例而不是创建新实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45033519/