Is it ok to return None from __new__?

空扰寡人 提交于 2019-12-06 00:42:51

问题


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?

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

  1. whether it might have other unforeseen issues
  2. whether it's a good programming practice to have constructors return None

Specific example:

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)

回答1:


It's not illegal. If nothing weird is done with the result, it will work.




回答2:


You should avoid this. The documentation doesn't exhaustively list the things you shouldn't do, but it says what __new__ should do: return an instance of the class.

If you don't want to return a new object in some cases, raise an exception.



来源:https://stackoverflow.com/questions/3860469/is-it-ok-to-return-none-from-new

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!