While experimenting, I wrote:
class Bag:
pass
g = Bag()
print(g)
Which gave me:
<__main__.Bag object at 0x00000000036F0748>
Which surprised me. I expected an error when I tried to initialize it, since I didn't define __init___.
Why isn't this the case?
You only need to override the methods you want to change.
In other words:
If you don't override __init__, the __init__ method of the superclass will be called.
E.g.
class Bag:
pass
if equivalent to:
class Bag:
def __init__(self):
super(Bag, self).__init__()
Furthermore, __init__ is indeed optional. It is an initializer for an instance.
When you instantiate a class (by calling it) the constructor for the class (class method __new__) is called. The constructor returns an instance for which __init__ is called.
So in practice even:
class Bag:
def __init__(self):
pass
Will work just fine.
__init__ is an intializer not the constructor, If an __init__ method is defined it is used just to initialize the created object with the values provided as arguments. An object anyhow gets created even if an __init__ method is not defined for the class, however not initialized, as __init__ method is not overridden to customize as per your needs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With