如何*不*创建实例

Rob*_*rto 2 python python-3.x

如果参数与预期值不匹配,我想避免创建实例.
即总之:

#!/usr/bin/env python3

class Test(object):
    def __init__(self, reallydoit = True):
        if reallydoit:
            self.done = True
        else:
            return None

make_me = Test()
make_me_not = Test(reallydoit=False)
Run Code Online (Sandbox Code Playgroud)

我想make_me_not成为None,我认为return None可以做到,但这个变量也是一个例子Test:

>>> make_me
<__main__.Test object at 0x7fd78c732390>
>>> make_me_not
<__main__.Test object at 0x7fd78c732470>
Run Code Online (Sandbox Code Playgroud)

我确定有办法做到这一点,但到目前为止,我的Google-fu让我失望了.
感谢您的任何帮助.

编辑:我宁愿这是默默处理; 条件应该被解释为"最好不要创建这个特定的实例"而不是"你正在以错误的方式使用这个类".所以是的,提出错误然后处理它是一种可能性,但我宁愿减少骚动.

Ray*_*ger 7

只需在__init__方法中引发异常:

class Test(object):
    def __init__(self, reallydoit = True):
        if reallydoit:
            self.done = True
        else:
            raise ValueError('Not really doing it')
Run Code Online (Sandbox Code Playgroud)

另一种方法是将代码移动到__new__方法:

class Test(object):
    def __new__(cls, reallydoit = True):
        if reallydoit:
            return object.__new__(cls)
        else:
            return None
Run Code Online (Sandbox Code Playgroud)

最后,您可以将创建决策移动到工厂函数中:

class Test(object):
    pass

def maybe_test(reallydoit=True):
    if reallydoit:
         return Test()
    return None
Run Code Online (Sandbox Code Playgroud)