python - 如何*不*创建实例

标签 python python-3.x

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

#!/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_notNone,我认为 return None 可以做到,但这个变量是测试也是:

>>> make_me
<__main__.Test object at 0x7fd78c732390>
>>> make_me_not
<__main__.Test object at 0x7fd78c732470>

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

编辑:我更希望静静地处理它;条件应解释为“最好不要创建此特定实例”而不是“您以错误的方式使用此类”。所以是的,提出错误然后处理它是可能的,但我更愿意少闹事。

最佳答案

只是raise __init__ 中的异常方法:

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

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

class Test(object):
    def __new__(cls, reallydoit = True):
        if reallydoit:
            return object.__new__(cls)
        else:
            return None

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

class Test(object):
    pass

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

关于python - 如何*不*创建实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39988779/

相关文章:

python - 使用颜色图在 mplot 3D 中表示 4D 数据

Python 和线程 : instance has no __call__ method

database - 在 Raymond Hettingers Pycon 2017 Talk 中,什么是数据库表示

Pythons 的 AttributeError : 'NoneType' object has no attribute 'errors'

python - 无法使用查找我的设备功能给我的手机响铃。事实上它甚至没有登录

python - 是否可以在 Networkx 图中混合不同形状的节点?

Python 请求奇怪的 URL %-编码

python - 从右到左和从左到右打印得很好

python-3.x - 如何在python中从服务器接收文件?

python - 如何在 python run_in_executor 方法调用中捕获异常