I just started learning Python from Learn Python The Hard Way by Zed A. Shaw. However, I am confused about when should one use the init method? Is it mandatory to use it? What happens of I don't?
-
Possible duplicate of [Python \_\_init\_\_ and self what do they do?](http://stackoverflow.com/questions/625083/python-init-and-self-what-do-they-do) – Stephen Rauch Jan 06 '17 at 16:01
1 Answers
Perhaps someone else has a better answer, but this is how I understand it. The metaphor of a blueprint for building a house works well here. Say you have a housing development with many different houses that look essentially the same with slight variations. Building a house requires that you do essentially the same thing each time, then adding customizations.
Your class declarations are like blueprints, telling your Python program everything it needs to know about a house. However, your __init__
method provides the instructions for the absolute basic requirements for that object.
Just like you can't have a house without a door, you can't have a Student
object or a Pet
object without a few basic properties like name, age. Your __init__
method will tell Python what it needs to do whenever you create a new Student or Pet, just like a blueprint will tell a general contractor that every house needs a door.
The __init__
method also establishes the object's self
variable. self
allows you to be specific about variable assignment for a single copy of a class.
Hope this helps!

- 121
- 3