Python: don't return from __init__()
March 01, 2007 |
co.mments
Returning a value from __init__() will cause an exception in Python:
In [1]: In [1]: class Foo: ...: def __init__(self): return self ...: ...: In [2]: In [2]: f = Foo() ---------------------------------------- exceptions.TypeError Traceback (most recent call last) TypeError: __init__() should return None In [3]:
That's because __init__() is not the call to cons in Python; it's an initializer called after object instantiation, though most people (myself included) will treat intuitively treat __init__() as the construction point, 'cos that what it looks like and it takes the same arguments logically as the constructor would. It's rare enough you see anyone returning from __init__ as the code will fail fast (not swallowing exceptions is a Python tenet). Usually it happens when a programmer has conditional logic in the initializer or is doing factory type stuff, all combinations of which didn't get executed during development and testing.
The construction method in python is __new__(). There's a bit of detail here - python basic customizations - and the cookbook has an example of overriding __new__().
March 1, 2007 11:37 PM
Comments
Post a comment
Trackback Pings
TrackBack URL for this entry:
http://www.dehora.net/mt/mt-tb.cgi/2050