Skip to content

Commit 75e70d3

Browse files
authored
Merge pull request #61 from josemoracard/jose10-add-3-class-exercises
Añadir ejercicio 042-understanding_classes
2 parents a9a79d9 + 2076909 commit 75e70d3

File tree

5 files changed

+153
-0
lines changed

5 files changed

+153
-0
lines changed

Diff for: exercises/042-understanding_classes/README.es.md

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# `042` understanding classes
2+
3+
En Python, una clase es una estructura que te permite organizar y encapsular datos y funcionalidades relacionadas. Las clases son una característica fundamental de la programación orientada a objetos (OOP), un paradigma de programación que utiliza objetos para modelar y organizar el código.
4+
5+
En términos simples, una clase es como un plano o un molde para crear objetos. Un objeto es una instancia específica de una clase que tiene atributos (datos) y métodos (funciones) asociados. Los atributos representan características del objeto, y los métodos representan las acciones que el objeto puede realizar.
6+
7+
## 📎 Ejemplo:
8+
9+
```py
10+
class Student:
11+
def __init__(self, name, age, grade): # Estos son sus atributos
12+
self.name = name
13+
self.age = age
14+
self.grade = grade
15+
16+
def introduce(self): # Esto es un método
17+
return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}."
18+
19+
def study(self, hours): # Esto es otro método
20+
self.grade += hours * 0.5
21+
return f"After studying for {hours} hours, {self.name}'s new grade is {self.grade}."
22+
23+
student1 = Student("Ana", 20, 80)
24+
25+
print(student1.introduce())
26+
print(student1.study(3))
27+
```
28+
29+
En este código:
30+
31+
+ La clase `Student` tiene un método `__init__` para inicializar los atributos *name*, *age* y *grade* del estudiante.
32+
+ `introduce` es un método que imprime un mensaje presentando al estudiante.
33+
+ `study` es un método que simula el acto de estudiar y actualiza la nota del estudiante.
34+
35+
## 📝 Instrucciones:
36+
37+
1. Para completar este ejercicio, copia el código proporcionado en el ejemplo y pégalo en tu archivo `app.py`. Ejecuta el código y prueba su funcionalidad. Experimenta con modificar diferentes aspectos del código para observar cómo se comporta. Este enfoque práctico te ayudará a comprender la estructura y el comportamiento de la clase `Student`. Una vez que te hayas familiarizado con el código y sus efectos, siéntete libre de pasar al siguiente ejercicio.
38+
39+
## 💡 Pistas:
40+
41+
+ Lee un poco sobre la función interna `__init__`: https://www.w3schools.com/python/gloss_python_class_init.asp
42+
43+
+ Si no comprendes la funcionalidad del parámetro `self` en el código que acabas de copiar, tómate un momento para visitar el siguiente enlace donde encontrarás una explicación detallada: [Entendiendo el parámetro 'self'](https://www.geeksforgeeks.org/self-in-python-class/)

Diff for: exercises/042-understanding_classes/README.md

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# `042` understanding classes
2+
3+
In Python, a class is a structure that allows you to organize and encapsulate related data and functionalities. Classes are a fundamental feature of object-oriented programming (OOP), a programming paradigm that uses objects to model and organize code.
4+
5+
In simple terms, a class is like a blueprint or a template for creating objects. An object is a specific instance of a class that has associated attributes (data) and methods (functions). Attributes represent the characteristics of the object, and methods represent the actions that the object can perform.
6+
7+
## 📎 Example:
8+
9+
```py
10+
class Student:
11+
def __init__(self, name, age, grade): # These are its attributes
12+
self.name = name
13+
self.age = age
14+
self.grade = grade
15+
16+
def introduce(self): # This is a method
17+
return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}."
18+
19+
def study(self, hours): # This is another method
20+
self.grade += hours * 0.5
21+
return f"After studying for {hours} hours, {self.name}'s new grade is {self.grade}."
22+
23+
student1 = Student("Ana", 20, 80)
24+
25+
print(student1.introduce())
26+
print(student1.study(3))
27+
```
28+
29+
In this code:
30+
31+
+ The `Student` class has an `__init__` method to initialize the attributes *name*, *age*, and *grade* of the student.
32+
+ `introduce` is a method that prints a message introducing the student.
33+
+ `study` is a method that simulates the act of studying and updates the student's grade.
34+
35+
## 📝 Instructions:
36+
37+
1. To complete this exercise, copy the provided code from the example and paste it into your `app.py` file. Execute the code and test its functionality. Experiment with modifying different aspects of the code to observe how it behaves. This hands-on approach will help you understand the structure and behavior of the `Student` class. Once you have familiarized yourself with the code and its effects, feel free to proceed to the next exercise.
38+
39+
## 💡 Hints:
40+
41+
+ Read about the `__init__` built-in function: https://www.w3schools.com/python/gloss_python_class_init.asp
42+
43+
+ If you find yourself wondering about the role of the `self` keyword in Python classes, take a moment to visit the following link for a detailed explanation: [Understanding the 'self' Parameter](https://www.geeksforgeeks.org/self-in-python-class/)

Diff for: exercises/042-understanding_classes/app.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Your code here

Diff for: exercises/042-understanding_classes/solution.hide.py

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
# Your code here
2+
class Student:
3+
def __init__(self, name, age, grade): # These are its attributes
4+
self.name = name
5+
self.age = age
6+
self.grade = grade
7+
8+
def introduce(self): # This is a method
9+
return f"Hello! I am {self.name}, I am {self.age} years old, and my current grade is {self.grade}."
10+
11+
def study(self, hours): # This is another method
12+
self.grade += hours * 0.5
13+
return f"After studying for {hours} hours, {self.name}'s new grade is {self.grade}."
14+
15+
student1 = Student("Ana", 20, 80)
16+
17+
print(student1.introduce())
18+
print(student1.study(3))

Diff for: exercises/042-understanding_classes/test.py

+48
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
import pytest
2+
from app import Student
3+
4+
@pytest.mark.it("The Student class should exist")
5+
def test_student_class_exists():
6+
try:
7+
assert Student
8+
except AttributeError:
9+
raise AttributeError("The class 'Student' should exist in app.py")
10+
11+
@pytest.mark.it("The Student class includes the 'name' attribute")
12+
def test_student_has_name_attribute():
13+
student = Student("John", 21, 75)
14+
assert hasattr(student, "name")
15+
16+
@pytest.mark.it("The Student class includes the 'age' attribute")
17+
def test_student_has_age_attribute():
18+
student = Student("John", 21, 75)
19+
assert hasattr(student, "age")
20+
21+
@pytest.mark.it("The Student class includes the 'grade' attribute")
22+
def test_student_has_grade_attribute():
23+
student = Student("John", 21, 75)
24+
assert hasattr(student, "grade")
25+
26+
@pytest.mark.it("The Student class includes the 'introduce' method")
27+
def test_student_has_introduce_method():
28+
student = Student("Alice", 22, 90)
29+
assert hasattr(student, "introduce")
30+
31+
@pytest.mark.it("The introduce method should return the expected string. Testing with different values")
32+
def test_student_introduce_method_returns_expected_string():
33+
student1 = Student("Alice", 22, 90)
34+
student2 = Student("Bob", 19, 85)
35+
assert student1.introduce() == "Hello! I am Alice, I am 22 years old, and my current grade is 90."
36+
assert student2.introduce() == "Hello! I am Bob, I am 19 years old, and my current grade is 85."
37+
38+
@pytest.mark.it("The Student class includes the 'study' method")
39+
def test_student_has_study_method():
40+
student = Student("John", 21, 75)
41+
assert hasattr(student, "study")
42+
43+
@pytest.mark.it("The study method should return the expected string. Testing with different values")
44+
def test_student_study_method_returns_expected_string():
45+
student1 = Student("Eve", 20, 78)
46+
student2 = Student("Charlie", 23, 88)
47+
assert student1.study(3) == "After studying for 3 hours, Eve's new grade is 79.5."
48+
assert student2.study(2) == "After studying for 2 hours, Charlie's new grade is 89.0."

0 commit comments

Comments
 (0)