-
Notifications
You must be signed in to change notification settings - Fork 169
añadido ejercicio 45-class_methods #66
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
alesanchezr
merged 3 commits into
4GeeksAcademy:master
from
josemoracard:jose13-ejercicio-45-class-method
Feb 14, 2024
Merged
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
64 changes: 64 additions & 0 deletions
exercises/045-class_methods/README.es.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
# `045` class methods | ||
|
||
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. | ||
|
||
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. | ||
|
||
```py | ||
class Person: | ||
total_people = 0 # Variable de clase para llevar el seguimiento del número total de personas | ||
|
||
def __init__(self, name, age): | ||
self.name = name | ||
self.age = age | ||
Person.total_people += 1 # Incrementa el recuento de total_people por cada nueva instancia | ||
|
||
@classmethod | ||
def get_total_people(cls): | ||
return cls.total_people | ||
|
||
# Creando instancias de Person | ||
person1 = Person("Alice", 25) | ||
person2 = Person("Bob", 16) | ||
|
||
# Usando el class method para obtener el número total de personas | ||
total_people = Person.get_total_people() | ||
print(f"Total People: {total_people}") | ||
``` | ||
|
||
En este ejemplo: | ||
|
||
+ El método de clase `get_total_people` devuelve el número total de personas creadas (instancias de la clase Persona). | ||
|
||
## 📝 Instrucciones: | ||
|
||
1. Crea una clase llamada `MathOperations`. | ||
|
||
2. Dentro de la clase, define lo siguiente: | ||
|
||
+ Una variable de clase llamada `pi` con un valor de `3.14159`. | ||
+ 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 = π ×ばつ radio2`. | ||
|
||
3. Utiliza el método de clase `calculate_circle_area` para calcular el área de un círculo con un radio de 5. | ||
|
||
4. Imprime el resultado. (No es necesario crear ninguna instancia) | ||
|
||
## 📎 Ejemplo de entrada: | ||
|
||
```py | ||
circle_area = MathOperations.calculate_circle_area(5) | ||
``` | ||
|
||
## 📎 Ejemplo de salida: | ||
|
||
```py | ||
# Circle Area: 78.53975 | ||
``` | ||
|
||
## 💡 Pistas: | ||
|
||
+ Recuerda, para crear un método de clase, utiliza el decorador `@classmethod` encima de la definición del método. | ||
|
||
+ ¿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. | ||
|
||
+ 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. |
65 changes: 65 additions & 0 deletions
exercises/045-class_methods/README.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,65 @@ | ||
# `045` class methods | ||
|
||
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. | ||
|
||
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. | ||
|
||
```py | ||
class Person: | ||
total_people = 0 # Class variable to keep track of the total number of people | ||
|
||
def __init__(self, name, age): | ||
self.name = name | ||
self.age = age | ||
Person.total_people += 1 # Increment the total_people count for each new instance | ||
|
||
@classmethod | ||
def get_total_people(cls): | ||
return cls.total_people | ||
|
||
# Creating instances of Person | ||
person1 = Person("Alice", 25) | ||
person2 = Person("Bob", 16) | ||
|
||
# Using the class method to get the total number of people | ||
total_people = Person.get_total_people() | ||
print(f"Total People: {total_people}") | ||
``` | ||
|
||
In this example: | ||
|
||
+ The class method `get_total_people` returns the total number of people created (instances of the Person class). | ||
|
||
## 📝 Instructions: | ||
|
||
1. Create a class called `MathOperations`. | ||
|
||
2. Inside the class, define the following: | ||
|
||
+ A class variable named `pi` with a value of `3.14159`. | ||
+ 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 = π ×ばつ radius2` | ||
|
||
3. Use the class method `calculate_circle_area` to calculate the area of a circle with a radius of 5. | ||
|
||
4. Print the result. (No need to create any instance) | ||
|
||
## 📎 Example input: | ||
|
||
```py | ||
circle_area = MathOperations.calculate_circle_area(5) | ||
``` | ||
|
||
## 📎 Example output: | ||
|
||
```py | ||
# Circle Area: 78.53975 | ||
``` | ||
|
||
|
||
## 💡 Hints: | ||
|
||
+ Remember, to create a class method, use the `@classmethod` decorator above the method definition. | ||
|
||
+ 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. | ||
|
||
+ 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. |
2 changes: 2 additions & 0 deletions
exercises/045-class_methods/app.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
# Your code here | ||
|
13 changes: 13 additions & 0 deletions
exercises/045-class_methods/solution.hide.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
# Your code here | ||
|
||
class MathOperations: | ||
pi = 3.14159 | ||
|
||
@classmethod | ||
def calculate_circle_area(cls, radius): | ||
area = cls.pi * radius ** 2 | ||
return area | ||
|
||
circle_area = MathOperations.calculate_circle_area(5) | ||
|
||
print(f"Circle Area: {circle_area}") |
25 changes: 25 additions & 0 deletions
exercises/045-class_methods/test.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,25 @@ | ||
import pytest | ||
from app import MathOperations | ||
|
||
@pytest.mark.it("The 'MathOperations' class should exist") | ||
def test_math_operations_class_exists(): | ||
try: | ||
assert MathOperations | ||
except AttributeError: | ||
raise AttributeError("The class 'MathOperations' should exist in app.py") | ||
|
||
|
||
@pytest.mark.it("The MathOperations class includes the 'calculate_circle_area' class method") | ||
def test_math_operations_has_calculate_circle_area_class_method(): | ||
assert hasattr(MathOperations, "calculate_circle_area") | ||
|
||
|
||
@pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area") | ||
def test_calculate_circle_area_class_method_returns_expected_area(): | ||
result = MathOperations.calculate_circle_area(5) | ||
assert result == 78.53975 | ||
|
||
@pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area. Testing with different values") | ||
def test_calculate_circle_area_class_method_returns_expected_area_for_radius_10(): | ||
result = MathOperations.calculate_circle_area(10) | ||
assert result == 314.159 |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.