如果参数与预期值不匹配,我想避免创建实例。
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_not
为 None
,我认为 return None
可以做到,但这个变量是测试
也是:
>>> make_me
<__main__.Test object at 0x7fd78c732390>
>>> make_me_not
<__main__.Test object at 0x7fd78c732470>
我确信有办法做到这一点,但我的 Google-fu 到目前为止让我失望了。
感谢您的任何帮助。
编辑:我更希望静静地处理它;条件应解释为“最好不要创建此特定实例”而不是“您以错误的方式使用此类”。所以是的,提出错误然后处理它是可能的,但我更愿意少闹事。
最佳答案
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/