Constructors and Instance Methods
Learn how to initialize objects with data using the __init__ method.
Learning Objectives
- Understand and use the `__init__` constructor
- Create objects with unique data
- Write methods that use object attributes
- Understand the life cycle of an object
Initializing Objects
Yesterday, we created an empty object and added attributes manually. In professional code, we use a Constructor to set up an object’s data as soon as it is created.
The __init__ Method
In Python, the constructor is a special method called __init__ (short for initialization). It runs automatically when you create a new object.
|
|
Instance Methods
Methods can use the data stored in the object to perform specific tasks.
|
|
Why use self?
Remember, self is how the method knows which object’s data to use. If you have two dogs, self.name ensures Rex says “Rex” and Bella says “Bella”.
Interactive Practice
Try building a Book class that takes title and author as arguments in the __init__ method. Add a method called get_description that returns a string like “Title by Author”.
Quiz
Complete this quiz with a minimum score of 80% to mark Day 16 as complete.
Discussion
Have questions or want to discuss this lesson? Join the conversation below!