Skip to content

Commit 4a20749

Browse files
authored
Merge pull request #67 from josemoracard/jose14-ejercicio-46-init_and_str_magic_methods
añadido ejercicio 42.1-init_and_str_methods
2 parents 3caf855 + e4e616c commit 4a20749

File tree

5 files changed

+157
-0
lines changed

5 files changed

+157
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
# `042.1` `__init__` and `__str__` methods
2+
3+
Normalmente, al trabajar con clases, te encontrarás con métodos de este estilo `__<método>__`; estos son conocidos como "métodos mágicos". Existen varios de ellos, y cada uno desempeña una función específica. En esta ocasión, nos enfocaremos en aprender dos de los más fundamentales.
4+
5+
El método mágico `__init__` es esencial para la inicialización de objetos dentro de una clase. Se ejecuta automáticamente cuando se crea una nueva instancia de la clase, permitiendo la asignación de valores iniciales a los atributos del objeto.
6+
7+
El método `__str__` se utiliza para proporcionar una representación de cadena legible de la instancia, permitiendo personalizar la salida cuando se imprime el objeto. Esto es especialmente útil para mejorar la legibilidad del código y facilitar la depuración, ya que define una versión amigable para humanos de la información contenida en el objeto.
8+
9+
## 📎 Ejemplo:
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+
## 📝 Instrucciones:
29+
30+
1. Crea una clase llamada `Book` que tenga los métodos `__init__` y `__str__`.
31+
32+
2. El método `__init__` debe inicializar los atributos `title`, `author` y `year`.
33+
34+
3. El método `__str__` debe devolver una cadena que represente la información de una instancia del siguiente libro de esta manera:
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+
## 💡 Pistas:
49+
50+
+ Utiliza el método `__init__` para inicializar los atributos de la instancia.
51+
52+
+ Utiliza el método `__str__` para proporcionar una representación de cadena legible de la instancia.
53+
54+
+ Para hacer saltos de línea dentro de un string puedes usar los siguientes caracteres `\n`.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
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.
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
# Your code here
2+
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
# Your code here
2+
3+
class Book:
4+
def __init__(self, title, author, year):
5+
self.title = title
6+
self.author = author
7+
self.year = year
8+
9+
def __str__(self):
10+
return f"Book Title: {self.title}\nAuthor: {self.author}\nYear: {self.year}"
11+
12+
book1 = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
13+
14+
print(book1)
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
import pytest
2+
from app import Book
3+
4+
@pytest.mark.it("The Book class exists")
5+
def test_book_class_exists():
6+
try:
7+
assert Book
8+
except AttributeError:
9+
raise AttributeError("The class 'Book' should exist in app.py")
10+
11+
@pytest.mark.it("The Book class has the __init__ method")
12+
def test_book_has_init_method():
13+
assert hasattr(Book, "__init__")
14+
15+
@pytest.mark.it("The __init__ method initializes the title, author, and year attributes")
16+
def test_init_method_initializes_attributes():
17+
book = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
18+
assert hasattr(book, "title")
19+
assert hasattr(book, "author")
20+
assert hasattr(book, "year")
21+
22+
@pytest.mark.it("The Book class has the __str__ method")
23+
def test_book_has_str_method():
24+
assert hasattr(Book, "__str__")
25+
26+
@pytest.mark.it("The __str__ method returns the expected string")
27+
def test_str_method_returns_expected_string(capsys):
28+
book = Book("The Great Gatsby", "F. Scott Fitzgerald", 1925)
29+
print(book)
30+
captured = capsys.readouterr()
31+
expected_output = "Book Title: The Great Gatsby\nAuthor: F. Scott Fitzgerald\nYear: 1925\n"
32+
assert captured.out == expected_output
33+

0 commit comments

Comments
 (0)