Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/batch-file/6.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何*不*创建实例_Python_Python 3.x - Fatal编程技术网

Python 如何*不*创建实例

Python 如何*不*创建实例,python,python-3.x,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(reallydo

如果参数与预期值不匹配,我希望避免创建实例。
简言之:

#!/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)
我希望
make_me_not
成为
None
,我认为
return None
可以做到这一点,但这个变量也是
Test
的一个实例:

>>> make_me
<__main__.Test object at 0x7fd78c732390>
>>> make_me_not
<__main__.Test object at 0x7fd78c732470>
>>让我
>>>让我不要
我肯定有办法做到这一点,但我的谷歌fu迄今为止让我失望。
谢谢你的帮助

编辑:我希望这是一个安静的处理方式;条件应该解释为“最好不要创建这个特定的实例”,而不是“你用错误的方式使用这个类”。因此,是的,提出一个错误并处理它是可能的,但我更喜欢少吵闹。

只是方法中的一个例外:

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

最后,您可以将创建决策移动到:


您可以尝试引发错误引发异常,或覆盖
\uuuu new\uuuu
而不是
\uuuu init\uuuu
。在构造函数中引发异常。这是处理坏的构造函数参数的标准方法。我已经更新了问题以澄清它,而
\uuuuu new\uuuu()
似乎是最好的选择。非常感谢。
class Test(object):
    def __init__(self, reallydoit = True):
        if reallydoit:
            self.done = True
        else:
            raise ValueError('Not really doing it')
class Test(object):
    def __new__(cls, reallydoit = True):
        if reallydoit:
            return object.__new__(cls)
        else:
            return None
class Test(object):
    pass

def maybe_test(reallydoit=True):
    if reallydoit:
         return Test()
    return None