Language: EN

tipos-de-metodos-en-python

Methods in Python Instance, Class, and Static

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

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

  • Instance Method: Used when the method needs to access or modify specific data of an instance

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

  • Static Method: 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 the instances of a class. They 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'm {self.name} and I'm {self.age} years old."

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

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

In this example

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

Class Methods

Class methods are methods that act on the class itself (instead of 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 relate to the class but do not require access to its attributes.

They are defined using the @staticmethod decorator, and do not depend on the instance (self) or the class (cls).

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.