问题
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
- whether it might have other unforeseen issues
- 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