如果__init __()中的条件不满足,则不要创建对象 [英] Don't create object when if condition is not met in __init__()

查看:69
本文介绍了如果__init __()中的条件不满足,则不要创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个映射数据库对象的类

I have a class that maps a database object

class MyObj:
    def __init__(self):
        ...SQL request with id as key...
        if len(rows) == 1:
            ...maps columns as my_obj attributes...
            self.exists = True
        else:
            self.exists = False

通过这种设计,每次都会创建一个对象,然后我们检查该对象是否存在于具有.exists属性的数据库中.

With such design, an object is created each time, and we check if it is present in database with .exists attribute.

my_obj = MyObj(id=15)
if my_obj.exists:
    ...do stuff...

有效.

但是我怀疑有一种更干净的初始化方法,我们只需要检查一下即可.

But I suspect there is a cleaner way to init, and we would just have to check like that:

 my_obj = MyObj(id=15)
 if my_obj:
     ...do stuff...

推荐答案

您不能在__init__中执行此操作,因为该方法在创建新实例后 后运行.

You can't do this in __init__, because that method is run after the new instance is created.

可以使用 ,但是首先运行它来创建实例.因为通常应该返回该新实例,所以您还可以选择返回其他内容(例如None).

You can do it with object.__new__() however, this is run to create the instance in the first place. Because it is normally supposed to return that new instance, you could also choose to return something else (like None).

您可以这样使用它:

class MyObj:
    def __new__(cls, id):
        # ...SQL request with id as key...
        if not rows:
            # no rows, so no data. Return `None`.
            return None

        # create a new instance and set attributes on it
        instance = super().__new__(cls)  # empty instance
        instance.rows = ...
        return instance

这篇关于如果__init __()中的条件不满足,则不要创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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