从__new__返回None是否可以? [英] Is it ok to return None from __new__?
本文介绍了从__new__返回None是否可以?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
通常,如果类的用户知道有时构造函数将评估为None,则从__new__
方法返回None是否合理?
In general, is it reasonable to return None from a __new__
method if the user of the class knows that sometimes the constructor will evaluate to None?
文档并不意味着它是非法的,而且我也看不到任何直接的问题(因为不会调用__init__
,没有一个不是所讨论的自定义类的实例!).但我担心
The documentation doesn't imply it's illegal, and I don't see any immediate problems (since __init__
is not going to be called, None not being an instance of the custom class in question!). But I'm worried about
- 是否还有其他不可预见的问题
- 让构造函数返回None是否是一种好的编程习惯
具体示例:
class MyNumber(int):
def __new__(cls, value): # value is a string (usually) parsed from a file
if value == 'N.A.':
return None
return int.__new__(cls, value)
推荐答案
这不是非法的.如果结果没有任何奇怪的事情,它将起作用.
It's not illegal. If nothing weird is done with the result, it will work.
这篇关于从__new__返回None是否可以?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文