Language: EN

tipos-de-metodos-en-python

Methods in Python Instance, Class, and Static

In Python, methods are functions defined within the definition of a class.

There are three types of methods that differ in how they are defined and what they have access to:

  • Instance Method: It is used when the method needs to access or modify data specific to an instance.

  • Class Method: It is used when the method needs to access data that belongs to the entire class, such as shared class attributes.

  • Static Method: It is used when the method does not depend on instance or class data and performs an independent operation.

Instance Methods

Instance methods are methods that act on instances of a class and have access to the attributes of those instances through the self parameter.

They are the most common methods in Python and are defined within a class using def.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def greet(self):
        return f"Hello, I am {self.name} and I am {self.age} years old."

# Creating an instance of Person
person1 = Person("Juan", 30)

# Calling the instance method
print(person1.greet())  # Output: Hello, I am Juan and I am 30 years old.

In this example:

  • greet() is an instance method.
  • It uses self to access the attributes name and age of the instance person1.

Class Methods

Class methods are methods that act on the class itself, rather than on individual instances of the class.

They are defined using the @classmethod decorator and have access to the class through the cls parameter.

class Car:
    discount = 0.1  # 10% discount for all cars

    def __init__(self, brand, model, price):
        self.brand = brand
        self.model = model
        self.price = price

    @classmethod
    def apply_discount(cls, price):
        return price * (1 - cls.discount)

# Using the class method
final_price = Car.apply_discount(30000)
print(f"Final price with discount: ${final_price}")  # Output: Final price with discount: $27000.0

In this example:

  • apply_discount() is a class method.
  • It uses cls to access the class attribute discount and apply a discount to the provided price.

Static Methods

Static methods are methods that do not depend on the instance (self) or the class (cls).

They are defined using the @staticmethod decorator and are methods that relate to the class but do not require access to its attributes.

class Utilities:
    @staticmethod
    def add(a, b):
        return a + b

# Using the static method
result = Utilities.add(3, 5)
print(f"Result of the addition: {result}")  # Output: Result of the addition: 8

In this example:

  • add() is a static method that performs a simple addition operation without needing to access instance or class attributes.