I would like to avoid the creation of an instance if the arguments do not match the expected values.
I.e. in short:
如果参数与期望值不匹配,我想避免创建实例。即简而言之:
#!/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)
I'd like make_me_not
to be None
, and I thought that return None
could do it, but this variable is an instance of Test
too:
我想make_me_not为None,我认为返回None可以做到,但是这个变量也是Test的一个实例:
>>> make_me
<__main__.Test object at 0x7fd78c732390>
>>> make_me_not
<__main__.Test object at 0x7fd78c732470>
I'm sure there's a way to do this, but my Google-fu failed me so far.
Thank you for any help.
我确定有办法做到这一点,但到目前为止,我的Google-fu让我失望了。感谢您的任何帮助。
EDIT: I would prefer this to be handled silently; the conditional should be interpreted as "Best not create this specific instance" instead of "You are using this class the wrong way". So yes, raising an error and then handling it is a possibility, but I'd prefer making less ruckus.
编辑:我希望这是默默处理;条件应该被解释为“最好不要创建这个特定的实例”而不是“你正在以错误的方式使用这个类”。所以是的,提出错误然后处理它是一种可能性,但我宁愿减少骚动。
1 个解决方案
#1
7
Just raise an exception in the __init__ method:
只需在__init__方法中引发异常:
class Test(object):
def __init__(self, reallydoit = True):
if reallydoit:
self.done = True
else:
raise ValueError('Not really doing it')
The other approach is to move your code to a __new__ method:
另一种方法是将代码移动到__new__方法:
class Test(object):
def __new__(cls, reallydoit = True):
if reallydoit:
return object.__new__(cls)
else:
return None
Lastly, you could move the creation decision into a factory function:
最后,您可以将创建决策移动到工厂函数中:
class Test(object):
pass
def maybe_test(reallydoit=True):
if reallydoit:
return Test()
return None
#1
7
Just raise an exception in the __init__ method:
只需在__init__方法中引发异常:
class Test(object):
def __init__(self, reallydoit = True):
if reallydoit:
self.done = True
else:
raise ValueError('Not really doing it')
The other approach is to move your code to a __new__ method:
另一种方法是将代码移动到__new__方法:
class Test(object):
def __new__(cls, reallydoit = True):
if reallydoit:
return object.__new__(cls)
else:
return None
Lastly, you could move the creation decision into a factory function:
最后,您可以将创建决策移动到工厂函数中:
class Test(object):
pass
def maybe_test(reallydoit=True):
if reallydoit:
return Test()
return None