返回类实例,而不是创建一个新的实例(如果已经存在) [英] Return class instance instead of creating a new one if already existing

查看:60
本文介绍了返回类实例,而不是创建一个新的实例(如果已经存在)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为正在进行的一些实验室实验的结果定义了一个名为 Experiment 的类。这个想法是创建一种数据库:如果我添加一个实验,它将在退出前被腌制到db中,并在启动时重新加载(并添加到类注册表中)。

I defined a class named Experiment for the results of some lab experiments I am conducting. The idea was to create a sort of database: if I add an experiment, this will be pickled to a db before at exit and reloaded (and added to the class registry) at startup.

我的班级定义是:

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 是用于检查包含t的文件的哈希值的函数他的结果是:

While fn.checkhash is a function that checks the hashes of the files containing the results:

def checkhash(hashdat):
    for exp in cl.Experiment:
        if exp.hashdat == hashdat:
            return exp
    return False

我添加了一个以前添加的实验,它不会被覆盖。

So that if I add a previously added experiment, this won't be overwritten.

是否可以以某种方式返回现有实例(如果已经存在)而不是引发错误? (我知道在 __ init __ 块中是不可能的)

Is it possible to somehow return the existing instance if already existant instead of raising an error? (I know in __init__ block it is not possible)

推荐答案

您如果您要自定义创建内容,而不仅仅是在新创建的对象中进行初始化,则可以使用 __ new __

You can use __new__ if you want to customize the creation instead of just initializing in newly created object:

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

这篇关于返回类实例,而不是创建一个新的实例(如果已经存在)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆