From a9e1b825dd27b8c86788eb6cbbf2e686fe35c8bd Mon Sep 17 00:00:00 2001 From: josemoracard Date: 2024年1月24日 12:29:02 +0000 Subject: [PATCH 1/3] =?UTF-8?q?a=C3=B1adido=20ejercicio=2045-class=5Fmetho?= =?UTF-8?q?ds?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- exercises/045-class_methods/README.es.md | 64 +++++++++++++++++++ exercises/045-class_methods/README.md | 65 ++++++++++++++++++++ exercises/045-class_methods/app.py | 2 + exercises/045-class_methods/solution.hide.py | 13 ++++ exercises/045-class_methods/test.py | 20 ++++++ 5 files changed, 164 insertions(+) create mode 100644 exercises/045-class_methods/README.es.md create mode 100644 exercises/045-class_methods/README.md create mode 100644 exercises/045-class_methods/app.py create mode 100644 exercises/045-class_methods/solution.hide.py create mode 100644 exercises/045-class_methods/test.py diff --git a/exercises/045-class_methods/README.es.md b/exercises/045-class_methods/README.es.md new file mode 100644 index 00000000..fa16c06b --- /dev/null +++ b/exercises/045-class_methods/README.es.md @@ -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. \ No newline at end of file diff --git a/exercises/045-class_methods/README.md b/exercises/045-class_methods/README.md new file mode 100644 index 00000000..bf41ec56 --- /dev/null +++ b/exercises/045-class_methods/README.md @@ -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. \ No newline at end of file diff --git a/exercises/045-class_methods/app.py b/exercises/045-class_methods/app.py new file mode 100644 index 00000000..6014a8e1 --- /dev/null +++ b/exercises/045-class_methods/app.py @@ -0,0 +1,2 @@ +# Your code here + diff --git a/exercises/045-class_methods/solution.hide.py b/exercises/045-class_methods/solution.hide.py new file mode 100644 index 00000000..260bedd8 --- /dev/null +++ b/exercises/045-class_methods/solution.hide.py @@ -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}") \ No newline at end of file diff --git a/exercises/045-class_methods/test.py b/exercises/045-class_methods/test.py new file mode 100644 index 00000000..d93dd930 --- /dev/null +++ b/exercises/045-class_methods/test.py @@ -0,0 +1,20 @@ +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 \ No newline at end of file From b2c03e8ac4015a394b9f4f38a8b6287d066946bd Mon Sep 17 00:00:00 2001 From: Jose Mora <109150320+josemoracard@users.noreply.github.com> Date: 2024年1月30日 14:45:56 +0100 Subject: [PATCH 2/3] Update test.py --- exercises/045-class_methods/test.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/exercises/045-class_methods/test.py b/exercises/045-class_methods/test.py index d93dd930..6e0215b7 100644 --- a/exercises/045-class_methods/test.py +++ b/exercises/045-class_methods/test.py @@ -17,4 +17,9 @@ def test_math_operations_has_calculate_circle_area_class_method(): @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 \ No newline at end of file + assert result == 78.53975 + +@pytest.mark.it("The 'calculate_circle_area' class method should return the expected circle area. Testing with another value") +def test_calculate_circle_area_class_method_returns_expected_area_for_radius_10(): + result = MathOperations.calculate_circle_area(10) + assert result == 314.159 From a8a6aee8b0348d177bfd6b564f47024eff3c110f Mon Sep 17 00:00:00 2001 From: Jose Mora <109150320+josemoracard@users.noreply.github.com> Date: 2024年1月30日 14:59:25 +0100 Subject: [PATCH 3/3] Update test.py --- exercises/045-class_methods/test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/exercises/045-class_methods/test.py b/exercises/045-class_methods/test.py index 6e0215b7..ec3cd670 100644 --- a/exercises/045-class_methods/test.py +++ b/exercises/045-class_methods/test.py @@ -19,7 +19,7 @@ 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 another value") +@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

AltStyle によって変換されたページ (->オリジナル) /