Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit c010ded

Browse files
Añadir ejercicio 044-static_and_class_method
1 parent b597f4f commit c010ded

File tree

4 files changed

+201
-0
lines changed

4 files changed

+201
-0
lines changed
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# `044` static and 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+
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í.
8+
9+
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.
10+
11+
```py
12+
class Person:
13+
total_people = 0 # Variable de clase para llevar el seguimiento del número total de personas
14+
15+
def __init__(self, name, age):
16+
self.name = name
17+
self.age = age
18+
Person.total_people += 1 # Incrementa el recuento de total_people por cada nueva instancia
19+
20+
@classmethod
21+
def get_total_people(cls):
22+
return cls.total_people
23+
24+
@staticmethod
25+
def is_adult(age):
26+
return age >= 18
27+
28+
# Creando instancias de Person
29+
person1 = Person("Alice", 25)
30+
person2 = Person("Bob", 30)
31+
32+
# Usando el class method para obtener el número total de personas
33+
total_people = Person.get_total_people()
34+
print(f"Total People: {total_people}")
35+
36+
# Usando el static method para verificar si una persona es adulta
37+
is_adult_person1 = Person.is_adult(person1.age)
38+
is_adult_person2 = Person.is_adult(person2.age)
39+
print(f"{person1.name} is an adult: {is_adult_person1}")
40+
print(f"{person2.name} is an adult: {is_adult_person2}")
41+
```
42+
43+
En este ejemplo:
44+
45+
+ El método de clase `get_total_people` devuelve el número total de personas creadas (instancias de la clase Persona).
46+
47+
+ 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.
48+
49+
## 📝 Instrucciones:
50+
51+
1. Crea una clase llamada `MathOperations`.
52+
53+
2. Dentro de la clase, define lo siguiente:
54+
55+
+ Una variable de clase llamada `pi` con un valor de `3.14159`.
56+
+ 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`.
57+
58+
3. Crea un método estático llamado `add_numbers` que tome dos números como parámetros y devuelva su suma.
59+
60+
4. Crea una instancia de la clase `MathOperations`.
61+
62+
5. Utiliza el método de clase `calculate_circle_area` para calcular el área de un círculo con un radio de 5.
63+
64+
6. Utiliza el método estático `add_numbers` para sumar dos números, por ejemplo, 10 y 15.
65+
66+
7. Imprime los resultados de cada operación.
67+
68+
## 📎 Ejemplo de entrada:
69+
70+
```py
71+
math_operations_instance = MathOperations()
72+
circle_area = MathOperations.calculate_circle_area(5)
73+
sum_of_numbers = MathOperations.add_numbers(10, 15)
74+
```
75+
76+
## 📎 Ejemplo de salida:
77+
78+
```py
79+
78.53975
80+
25
81+
```
82+
83+
## 💡 Pistas:
84+
85+
+ Recuerda, para crear un método de clase, utiliza el decorador `@classmethod` encima de la definición del método.
86+
87+
+ Recuerda, para crear un método estático, utiliza el decorador `@staticmethod` encima de la definición del método.
88+
89+
+ 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).
Lines changed: 89 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,89 @@
1+
# `044` static and 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+
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.
8+
9+
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.
10+
11+
```py
12+
class Person:
13+
total_people = 0 # Class variable to keep track of the total number of people
14+
15+
def __init__(self, name, age):
16+
self.name = name
17+
self.age = age
18+
Person.total_people += 1 # Increment the total_people count for each new instance
19+
20+
@classmethod
21+
def get_total_people(cls):
22+
return cls.total_people
23+
24+
@staticmethod
25+
def is_adult(age):
26+
return age >= 18
27+
28+
# Creating instances of Person
29+
person1 = Person("Alice", 25)
30+
person2 = Person("Bob", 30)
31+
32+
# Using the class method to get the total number of people
33+
total_people = Person.get_total_people()
34+
print(f"Total People: {total_people}")
35+
36+
# Using the static method to check if a person is an adult
37+
is_adult_person1 = Person.is_adult(person1.age)
38+
is_adult_person2 = Person.is_adult(person2.age)
39+
print(f"{person1.name} is an adult: {is_adult_person1}")
40+
print(f"{person2.name} is an adult: {is_adult_person2}")
41+
```
42+
43+
In this example:
44+
45+
+ The class method `get_total_people` returns the total number of people created (instances of the Person class).
46+
47+
+ 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.
48+
49+
## 📝 Instructions:
50+
51+
1. Create a class called `MathOperations`.
52+
53+
2. Inside the class, define the following:
54+
55+
+ A class variable named `pi` with a value of `3.14159`.
56+
+ 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`
57+
58+
3. Create a static method named `add_numbers` that takes two numbers as parameters and returns their sum.
59+
60+
4. Create an instance of the `MathOperations` class.
61+
62+
5. Use the class method `calculate_circle_area` to calculate the area of a circle with a radius of 5.
63+
64+
6. Use the static method `add_numbers` to add two numbers, for example, 10 and 15.
65+
66+
7. Print the results of each operation.
67+
68+
## 📎 Example input:
69+
70+
```py
71+
math_operations_instance = MathOperations()
72+
circle_area = MathOperations.calculate_circle_area(5)
73+
sum_of_numbers = MathOperations.add_numbers(10, 15)
74+
```
75+
76+
## 📎 Example output:
77+
78+
```py
79+
# Circle Area: 78.53975
80+
# Sum of Numbers: 25
81+
```
82+
83+
## 💡 Hints:
84+
85+
+ Remember, to create a class method, use the `@classmethod` decorator above the method definition.
86+
87+
+ Remember, To create a static method, use the `@staticmethod` decorator above the method definition.
88+
89+
+ 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).
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# Your code here
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
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+
@staticmethod
12+
def add_numbers(num1, num2):
13+
return num1 + num2
14+
15+
16+
math_operations_instance = MathOperations()
17+
circle_area = MathOperations.calculate_circle_area(5)
18+
sum_of_numbers = MathOperations.add_numbers(10, 15)
19+
20+
21+
print(f"Circle Area: {circle_area}")
22+
print(f"Sum of Numbers: {sum_of_numbers}")

0 commit comments

Comments
(0)

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