[Tutor] __new__ and __init__
Alan Gauld
alan.gauld at btinternet.com
Thu Aug 2 10:36:23 CEST 2012
On 01/08/12 15:28, rail shafigulin wrote:
> I'm trying to understand how to use the two methods. I know that __new__
> is used to create an object, while __init__ to initialize. But I'm not
> sure what happens when I create an object.
Use print statements to find out...
>>> class C(object):
... def __new__(cls):
... print 'in new'
... return object.__new__(cls)
... def __init__(slf): print 'in init'
...
>>> c = C()
in new
in init
>>>
> 1) Does it mean that __new__ and __init__ must have the same parameters?
> In this particular case __new__ and __init__ both have model_name and if
> I understand correctly when __new__ is called the rest of the parameters
> (air, tilt, cruise_control, etc) are absorbed by the *args argument.
That's right and I've never tried doing it differently
- but again the >>> prompt and print are your friends
> 2) What happens if I don't use the same parameters, say in the case of
> __init__ I will remove model_name, will I still be able to call dx =
> CarModel("Fix DX")
>
The best way to be sure is to try it. That's the joy of an interactive
prompt... you never need to guess.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list