如果__init __()中的条件不满足,则不要创建对象 [英] Don't create object when if condition is not met in __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屋!