[Tutor] __init__

Steven D'Aprano steve at pearwood.info
Wed Aug 31 11:23:58 EDT 2016


On Tue, Aug 30, 2016 at 09:08:13PM +0000, monikajg at netzero.net wrote:
> OK so somebodys remark that there is a default __init__ provided was not correct. 

It is correct. The default __init__ is provided by object, the root of 
the class hierarchy.

> What about old style classes? When we have a class that has no parent. 
> and it does not inherit from object since it is old class - and this 
> class has no __init__, does __new__ call __init__?

For old-style classes, __new__ doesn't exist at all. The behaviour of 
creating a new instance is hard-coded into the interpreter, and __init__ 
is only called if it exists. You can define a method __new__, but it 
won't be called:

# In Python 2

py> class NewStyle(object):
...     def __new__(cls):
...             print "called __new__"
...             return super(NewStyle, cls).__new__(cls)
...     def __init__(self):
...             print "called __init__"
...
py> instance = NewStyle()
called __new__
called __init__
py>
py> class OldStyle:
...     def __new__(cls):
...             print "called __new__"
...             return super(OldStyle, cls).__new__(cls)
...     def __init__(self):
...             print "called __init__"
...
py> instance = OldStyle()
called __init__


In Python 3, old-style classes are gone. Even in Python 2, they're 
discouraged.




-- 
Steve


More information about the Tutor mailing list