temporary_user_name
temporary_user_name

Reputation: 37058

Why is __init__ apparently optional?

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?

Upvotes: 4

Views: 401

Answers (3)

Yani
Yani

Reputation: 1535

You do not need to include the __init__ method if you do not intend on adding/changing it's functionality. Everything in python is an object and python objects have a number of built in methods, some of which you may include when creating your own object and some of which you may not. This is not a bad reference for learning about built in methods.

http://www.rafekettler.com/magicmethods.html

I might add one thing. If you intend on using the super function, it is a good idea to define objects which inherit from object. Perhaps this is not required in python 3+ but it is certainly true for some of the older versions.

class Bag(object):
    def __init__(self):
        super(Bag, self).__init__()
        # Adding extra functionality here.

Upvotes: 1

Kimvais
Kimvais

Reputation: 39548

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.

Upvotes: 10

pythoneer.farhat
pythoneer.farhat

Reputation: 11

__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.

Upvotes: 1

Related Questions