Skip to content

Commit 244f813

Browse files
authored
Merge pull request #63 from josemoracard/jose12-add-3-class-exercises
Añadir ejercicio 044-static_and_class_method
2 parents 75e70d3 + ec29f98 commit 244f813

File tree

5 files changed

+160
-0
lines changed

5 files changed

+160
-0
lines changed
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# `044` static methods
2+
3+
Un **método estático** en Python es un método que está vinculado a una clase en lugar de a una instancia de la clase. A diferencia de los métodos regulares, los métodos estáticos no tienen acceso a la instancia o a la clase en sí.
4+
5+
Los métodos estáticos se utilizan a menudo cuando un método en particular no depende del estado de la instancia o de la clase. Son más parecidos a funciones de utilidad asociadas con una clase.
6+
7+
```py
8+
class Person:
9+
10+
def __init__(self, name, age):
11+
self.name = name
12+
self.age = age
13+
14+
@staticmethod
15+
def is_adult(age):
16+
return age >= 18
17+
18+
# Creando instancias de Person
19+
person1 = Person("Alice", 25)
20+
person2 = Person("Bob", 16)
21+
22+
# Usando el static method para verificar si una persona es adulta
23+
is_adult_person1 = Person.is_adult(person1.age)
24+
is_adult_person2 = Person.is_adult(person2.age)
25+
print(f"{person1.name} is an adult: {is_adult_person1}")
26+
print(f"{person2.name} is an adult: {is_adult_person2}")
27+
```
28+
29+
En este ejemplo:
30+
31+
+ El método estático `is_adult` verifica si una persona es adulta según su edad. No tiene acceso a variables de instancia o de clase directamente.
32+
33+
## 📝 Instrucciones:
34+
35+
1. Crea una clase llamada `MathOperations`.
36+
37+
2. Crea un método estático llamado `add_numbers` que tome dos números como parámetros y devuelva su suma.
38+
39+
3. Crea una instancia de la clase `MathOperations`.
40+
41+
4. Utiliza el método estático `add_numbers` para sumar dos números, por ejemplo, 10 y 15.
42+
43+
5. Imprime el resultado.
44+
45+
## 📎 Ejemplo de entrada:
46+
47+
```py
48+
math_operations_instance = MathOperations()
49+
sum_of_numbers = MathOperations.add_numbers(10, 15)
50+
```
51+
52+
## 📎 Ejemplo de salida:
53+
54+
```py
55+
# Sum of Numbers: 25
56+
```
57+
58+
## 💡 Pistas:
59+
60+
+ Recuerda, para crear un método estático, utiliza el decorador `@staticmethod` encima de la definición del método.
61+
62+
+ Cualquier cosa que aún no entiendas completamente, te animamos a que siempre utilices las herramientas que te ofrece internet para buscar información y aclarar la mayoría de tus dudas (todos los desarrolladores hacen esto, no te preocupes).
+62
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,62 @@
1+
# `044` static methods
2+
3+
A **static method** in Python is a method that is bound to a class rather than an instance of the class. Unlike regular methods, static methods don't have access to the instance or class itself.
4+
5+
Static methods are often used when a particular method does not depend on the state of the instance or the class. They are more like utility functions associated with a class.
6+
7+
```py
8+
class Person:
9+
10+
def __init__(self, name, age):
11+
self.name = name
12+
self.age = age
13+
14+
@staticmethod
15+
def is_adult(age):
16+
return age >= 18
17+
18+
# Creating instances of Person
19+
person1 = Person("Alice", 25)
20+
person2 = Person("Bob", 16)
21+
22+
# Using the static method to check if a person is an adult
23+
is_adult_person1 = Person.is_adult(person1.age)
24+
is_adult_person2 = Person.is_adult(person2.age)
25+
print(f"{person1.name} is an adult: {is_adult_person1}")
26+
print(f"{person2.name} is an adult: {is_adult_person2}")
27+
```
28+
29+
In this example:
30+
31+
+ The static method `is_adult` checks if a person is an adult based on their age. It doesn't have access to instance or class variables directly.
32+
33+
## 📝 Instructions:
34+
35+
1. Create a class called `MathOperations`.
36+
37+
2. Create a static method named `add_numbers` that takes two numbers as parameters and returns their sum.
38+
39+
3. Create an instance of the `MathOperations` class.
40+
41+
4. Use the static method `add_numbers` to add two numbers, for example, 10 and 15.
42+
43+
5. Print the result.
44+
45+
## 📎 Example input:
46+
47+
```py
48+
math_operations_instance = MathOperations()
49+
sum_of_numbers = MathOperations.add_numbers(10, 15)
50+
```
51+
52+
## 📎 Example output:
53+
54+
```py
55+
# Sum of Numbers: 25
56+
```
57+
58+
## 💡 Hints:
59+
60+
+ Remember, To create a static method, use the `@staticmethod` decorator above the method definition.
61+
62+
+ For anything you still don't fully get, we encourage you to always use the tools the internet provides you to search for information and clear most of your doubts (all developers do this, don't worry).

exercises/044-static_methods/app.py

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Your code here
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
# Your code here
2+
3+
class MathOperations:
4+
5+
@staticmethod
6+
def add_numbers(num1, num2):
7+
return num1 + num2
8+
9+
# You can call the static method without creating an instance
10+
sum_of_numbers = MathOperations.add_numbers(10, 15)
11+
12+
print(f"Sum of Numbers: {sum_of_numbers}")

exercises/044-static_methods/test.py

+23
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
import pytest
2+
from app import MathOperations
3+
4+
@pytest.mark.it("The 'MathOperations' class should exist")
5+
def test_math_operations_class_exists():
6+
try:
7+
assert MathOperations
8+
except AttributeError:
9+
raise AttributeError("The class 'MathOperations' should exist in app.py")
10+
11+
@pytest.mark.it("The MathOperations class includes the 'add_numbers' static method")
12+
def test_math_operations_has_add_numbers_static_method():
13+
assert hasattr(MathOperations, "add_numbers")
14+
15+
@pytest.mark.it("The 'add_numbers' static method should return the expected sum")
16+
def test_add_numbers_static_method_returns_expected_sum():
17+
result = MathOperations.add_numbers(5, 7)
18+
assert result == 12
19+
20+
@pytest.mark.it("The 'add_numbers' static method should return the expected sum. Testing with different values")
21+
def test_add_numbers_static_method_returns_expected_sum_for_different_values():
22+
result = MathOperations.add_numbers(10, 20)
23+
assert result == 30

0 commit comments

Comments
 (0)