Skip to content

Commit 3caf855

Browse files
authoredFeb 14, 2024
Merge pull request #66 from josemoracard/jose13-ejercicio-45-class-method
añadido ejercicio 45-class_methods
2 parents 244f813 + a8a6aee commit 3caf855

File tree

5 files changed

+169
-0
lines changed

5 files changed

+169
-0
lines changed
 

Diff for: ‎exercises/045-class_methods/README.es.md

+64
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
# `045` class methods
2+
3+
Un **método de clase** es un método que está vinculado a la clase y no a la instancia de la clase. Toma la clase misma como su primer parámetro, a menudo llamado "cls". Los métodos de clase se definen utilizando el decorador @classmethod.
4+
5+
La característica principal de un método de clase es que puede acceder y modificar atributos a nivel de clase, pero no puede acceder ni modificar atributos específicos de la instancia, ya que no tiene acceso a una instancia de la clase. Los métodos de clase se utilizan a menudo para tareas que involucran a la clase en sí misma en lugar de a instancias individuales.
6+
7+
```py
8+
class Person:
9+
total_people = 0 # Variable de clase para llevar el seguimiento del número total de personas
10+
11+
def __init__(self, name, age):
12+
self.name = name
13+
self.age = age
14+
Person.total_people += 1 # Incrementa el recuento de total_people por cada nueva instancia
15+
16+
@classmethod
17+
def get_total_people(cls):
18+
return cls.total_people
19+
20+
# Creando instancias de Person
21+
person1 = Person("Alice", 25)
22+
person2 = Person("Bob", 16)
23+
24+
# Usando el class method para obtener el número total de personas
25+
total_people = Person.get_total_people()
26+
print(f"Total People: {total_people}")
27+
```
28+
29+
En este ejemplo:
30+
31+
+ El método de clase `get_total_people` devuelve el número total de personas creadas (instancias de la clase Persona).
32+
33+
## 📝 Instrucciones:
34+
35+
1. Crea una clase llamada `MathOperations`.
36+
37+
2. Dentro de la clase, define lo siguiente:
38+
39+
+ Una variable de clase llamada `pi` con un valor de `3.14159`.
40+
+ Un método de clase llamado `calculate_circle_area` que tome un radio como parámetro y devuelva el área de un círculo utilizando la fórmula: `area = π × radio²`.
41+
42+
3. Utiliza el método de clase `calculate_circle_area` para calcular el área de un círculo con un radio de 5.
43+
44+
4. Imprime el resultado. (No es necesario crear ninguna instancia)
45+
46+
## 📎 Ejemplo de entrada:
47+
48+
```py
49+
circle_area = MathOperations.calculate_circle_area(5)
50+
```
51+
52+
## 📎 Ejemplo de salida:
53+
54+
```py
55+
# Circle Area: 78.53975
56+
```
57+
58+
## 💡 Pistas:
59+
60+
+ Recuerda, para crear un método de clase, utiliza el decorador `@classmethod` encima de la definición del método.
61+
62+
+ ¿Atascado? Si tienes alguna pregunta, ponte en contacto con tus profesores, compañeros de clase, o utiliza el canal de Slack `#public-support-full-stack` para aclarar tus dudas.
63+
64+
+ Cuando termines con este ejercicio, añade el `@staticmethod` del ejercicio anterior a tu clase y tómate tu tiempo para entender sus diferencias y el porqué de cada uno.

Diff for: ‎exercises/045-class_methods/README.md

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
# `045` class methods
2+
3+
A **class method** is a method that is bound to the class and not the instance of the class. It takes the class itself as its first parameter, often named "cls". Class methods are defined using the @classmethod decorator.
4+
5+
The primary characteristic of a class method is that it can access and modify class-level attributes, but it cannot access or modify instance-specific attributes since it doesn't have access to an instance of the class. Class methods are often used for tasks that involve the class itself rather than individual instances.
6+
7+
```py
8+
class Person:
9+
total_people = 0 # Class variable to keep track of the total number of people
10+
11+
def __init__(self, name, age):
12+
self.name = name
13+
self.age = age
14+
Person.total_people += 1 # Increment the total_people count for each new instance
15+
16+
@classmethod
17+
def get_total_people(cls):
18+
return cls.total_people
19+
20+
# Creating instances of Person
21+
person1 = Person("Alice", 25)
22+
person2 = Person("Bob", 16)
23+
24+
# Using the class method to get the total number of people
25+
total_people = Person.get_total_people()
26+
print(f"Total People: {total_people}")
27+
```
28+
29+
In this example:
30+
31+
+ The class method `get_total_people` returns the total number of people created (instances of the Person class).
32+
33+
## 📝 Instructions:
34+
35+
1. Create a class called `MathOperations`.
36+
37+
2. Inside the class, define the following:
38+
39+
+ A class variable named `pi` with a value of `3.14159`.
40+
+ A class method named `calculate_circle_area` that takes a radius as a parameter and returns the area of a circle using the formula: `area = π × radius²`
41+
42+
3. Use the class method `calculate_circle_area` to calculate the area of a circle with a radius of 5.
43+
44+
4. Print the result. (No need to create any instance)
45+
46+
## 📎 Example input:
47+
48+
```py
49+
circle_area = MathOperations.calculate_circle_area(5)
50+
```
51+
52+
## 📎 Example output:
53+
54+
```py
55+
# Circle Area: 78.53975
56+
```
57+
58+
59+
## 💡 Hints:
60+
61+
+ Remember, to create a class method, use the `@classmethod` decorator above the method definition.
62+
63+
+ Stuck? if you have any questions, reach out to your teachers, classmates, or use the Slack `#public-support-full-stack` channel to clear your doubts.
64+
65+
+ When you finish this exercise, add the `@staticmethod` from the previous exercise to your class and take your time to understand their differences and the reasons behind each one.

Diff for: ‎exercises/045-class_methods/app.py

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

Diff for: ‎exercises/045-class_methods/solution.hide.py

+13
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,13 @@
1+
# Your code here
2+
3+
class MathOperations:
4+
pi = 3.14159
5+
6+
@classmethod
7+
def calculate_circle_area(cls, radius):
8+
area = cls.pi * radius ** 2
9+
return area
10+
11+
circle_area = MathOperations.calculate_circle_area(5)
12+
13+
print(f"Circle Area: {circle_area}")

Diff for: ‎exercises/045-class_methods/test.py

+25
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
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+
12+
@pytest.mark.it("The MathOperations class includes the 'calculate_circle_area' class method")
13+
def test_math_operations_has_calculate_circle_area_class_method():
14+
assert hasattr(MathOperations, "calculate_circle_area")
15+
16+
17+
@pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area")
18+
def test_calculate_circle_area_class_method_returns_expected_area():
19+
result = MathOperations.calculate_circle_area(5)
20+
assert result == 78.53975
21+
22+
@pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area. Testing with different values")
23+
def test_calculate_circle_area_class_method_returns_expected_area_for_radius_10():
24+
result = MathOperations.calculate_circle_area(10)
25+
assert result == 314.159

0 commit comments

Comments
 (0)
Please sign in to comment.