[英]How to return None while declaring Class instance
MyClass
which is defined below accepts a single argument arg
. 下面定义的MyClass
接受单个参数arg
。
class MyClass(object):
def __init__(self, arg):
super(MyClass, self).__init__()
if not isinstance(arg, int):
return None
else:
self.arg = arg
If the incoming argument arg
is not an integer I would like to return None instead of the instance of MyClass
. 如果传入的参数arg
不是整数,我想返回None而不是MyClass
的实例。
a = MyClass(arg='Text Argument')
But even while MyClass
constructor __init__
returns None when the arg
is not an integer the resulting variable a
is still an instance of MyClass
: 但是,即使当arg
不是整数时, MyClass
构造函数__init__
返回None,结果变量a
仍然是MyClass
一个实例:
print a
<__main__.MyClass object at 0x0000000001FDEFD0>
How to make sure the variable a
remains None
if MyClass
is given a non-integer argument? 如果MyClass
被赋予非整数参数,如何确保变量a
仍为None
?
You should not return None
from a constructor, even if it was possible. 您不应该从构造函数返回None
,即使它是可能的。 The result of MyClass()
should always be an instance of MyClass
or a compatible class; MyClass()
的结果应该始终是MyClass
的实例或兼容的类; anything else would be Very Surprising And Error Inducing Behaviour™. 其他任何东西都会非常令人惊讶和错误诱导行为™。
You could do this with a custom __new__
method, which creates the actual instance. 您可以使用自定义__new__
方法执行此操作,该方法可创建实际实例。 But again, I would not recommend it. 但同样,我不会推荐它。
You should be raising an exception if the object cannot be constructed with the given data: 如果无法使用给定数据构造对象, 则应引发异常:
class MyClass(object):
def __init__(self, arg):
super(MyClass, self).__init__()
if not isinstance(arg, int):
raise TypeError('arg must be an int')
...
You generally should not be doing this, but you could if you want to, by overriding your __new__
, where the new instance is created: 你通常不应该这样做,但如果你想通过覆盖 __new__
,你可以创建新实例 :
class MyClass(object):
def __new__(cls, **kwargs):
if not isinstance(kwargs['arg'], int):
return None
return super(MyClass, cls).__new__(cls, **kwargs)
def __init__(self, arg):
super(MyClass, self).__init__()
self.arg = arg
The __init__
method does not create the instance, it only initializes it, returning None
from it is what is expected. __init__
方法不创建实例,它只初始化它,返回None
是预期的。
In the case __new__
returns an object that is not an instance (like None
in this case), __init__
will not be called. 如果__new__
返回一个不是实例的对象(在本例中为None
),则不会调用__init__
。
One of the reasons why you should not use the above is the following: 您不应该使用上述内容的原因之一如下:
print isinstance(MyClass(arg='666'), MyClass) #-> False
# waaah!
A lot of things will start to break in your code, and the above is only just one example. 你的代码中有很多东西会开始破坏,上面只是一个例子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.