[Tutor] __init__() - is it required?
Steven D'Aprano
steve at pearwood.info
Sun Jan 9 22:27:16 CET 2011
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()
>>>
--
Steven
More information about the Tutor
mailing list