如果条件不是m,如何从对象返回并删除对象

2024-03-28 23:22:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我想要一个在满足特定条件时不创建对象的类

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

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


Tags: andofselfinputgetifhereinit
1条回答
网友
1楼 · 发布于 2024-03-28 23:22:19

我建议提出一个例外

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

相关问题 更多 >