|
| 1 | +# `042.1` `__init__` and `__str__` methods |
| 2 | + |
| 3 | +Typically, when working with classes, you will encounter methods of the form `__<method>__`; these are known as "magic methods." There are a lot of them, each serving a specific purpose. This time, we will focus on learning two of the most fundamental ones. |
| 4 | + |
| 5 | +The magic method `__init__` is essential for the initialization of objects within a class. It is automatically executed when a new instance of the class is created, allowing for the assignment of initial values to the object's attributes. |
| 6 | + |
| 7 | +The `__str__` method is used to provide a readable string representation of the instance, allowing customization of the output when the object is printed. This is especially useful for improving code readability and facilitating debugging, as it defines a human-friendly version of the information contained in the object. |
| 8 | + |
| 9 | +## 📎 Example: |
| 10 | + |
| 11 | +```py |
| 12 | +class Person: |
| 13 | + def __init__(self, name, age, gender): |
| 14 | + self.name = name |
| 15 | + self.age = age |
| 16 | + self.gender = gender |
| 17 | + |
| 18 | + def __str__(self): |
| 19 | + return f"{self.name}, {self.age} years old, {self.gender}" |
| 20 | + |
| 21 | +# Create an instance of the Person class |
| 22 | +person1 = Person("Juan", 25, "Male") |
| 23 | + |
| 24 | +# Print the information of the person using the __str__ method |
| 25 | +print(person1) # Output: Juan, 25 years old, Male |
| 26 | +``` |
| 27 | + |
| 28 | +## 📝 Instructions: |
| 29 | + |
| 30 | +1. Create a class called `Book` that has the `__init__` and `__str__` methods. |
| 31 | + |
| 32 | +2. The `__init__` method should initialize the `title`, `author`, and `year` attributes. |
| 33 | + |
| 34 | +3. The `__str__` method should return a string representing the information of an instance of the following book in this manner: |
| 35 | + |
| 36 | +```py |
| 37 | +book1 = ("The Great Gatsby", "F. Scott Fitzgerald", 1925) |
| 38 | + |
| 39 | +print(book1) |
| 40 | + |
| 41 | +# Output: |
| 42 | +# |
| 43 | +# Book Title: The Great Gatsby |
| 44 | +# Author: F. Scott Fitzgerald |
| 45 | +# Year: 1925 |
| 46 | +``` |
| 47 | + |
| 48 | +## 💡 Hints: |
| 49 | + |
| 50 | ++ Use the `__init__` method to initialize the instance's attributes. |
| 51 | + |
| 52 | ++ Use the `__str__` method to provide a readable string representation of the instance. |
| 53 | + |
| 54 | ++ To create line breaks within a string, you can use the `\n` characters. |
0 commit comments