[Tutor] __init__() - is it required?

Corey Richardson kb1pkl at aim.com
Mon Jan 10 22:25:24 CET 2011


On 01/09/2011 04:27 PM, Steven D'Aprano wrote:
> Corey Richardson wrote:
>> Do all classes need an __init__() method? I have classes that look much
>> like this one starts out:
>>
>> class GenerateXML(object):
>>     """Defines methods to be inherited for StaticXML and AnimationXML"""
>>     def __init__(self):
>>         pass
>>
>> I would rather not do that. Code without it runs fine, but will there be
>> any negative consequences down the road? Does object define an __init__
>> method for me?
> 
> You don't need to define an __init__ if you don't need one. A 
> placeholder __init__ that does nothing, as above, is a waste of space.
> 
> object includes an __init__ method that not only does nothing, but 
> ignores any arguments you pass to it:
> 
>  >>> object.__init__
> <slot wrapper '__init__' of 'object' objects>
>  >>> object.__init__(1, 2, 3)
>  >>>
> 
> In Python 2.x, you can have "old-style" classes that don't inherit from 
> object. They too don't need an __init__:
> 
>  >>> class Old:  # *don't* inherit from object
> ...     pass
> ...
>  >>> o = Old()
>  >>>
> 
> 

Thank you very much Alan and Steven!

~Corey Richardson


More information about the Tutor mailing list