首页 > 解决方案 > 如果不满足条件,如何从对象返回和删除

问题描述

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

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

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

标签: pythonobjectexit

解决方案


我建议提出一个例外

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

推荐阅读