Don't create object when if condition is not met in __init__()

后端 未结 1 1074
迷失自我
迷失自我 2021-01-12 10:34

I have a class that maps a database object

class MyObj:
    def __init__(self):
        ...SQL request with id as key...
        if len(rows) == 1:
                  


        
相关标签:
1条回答
  • 2021-01-12 11:19

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

    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).

    You could use it like this:

    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
    
    0 讨论(0)
提交回复
热议问题