如果不满足条件,我该如何返回并删除对象

时间:2019-01-09 07:56:39

标签: python object exit

我想要一个如果满足特定条件就不会创建对象的类

class MyClass:
    def __init__(self, input):
        if input == condition:
          # get out of here and destroy this object to save memory
        self.var1 = input;
        # etc...

满足条件后,对象将被销毁。

1 个答案:

答案 0 :(得分:0)

我建议提出一个例外

class BadInitArgs(Exception):
    pass

class MyClass:
    def __init__(self, input):
        if input != "expected":
          raise BadInitArgs
          # get out of here and destroy this object to save memor
        # etc...

a = MyClass("expected")
b = MyClass("unexpected")