Sobes.tech
Junior

What methods are available in Python classes?

sobes.tech AI

Answer from AI

In Python, classes can have the following types of methods:

  1. Instance Methods Take self as the first argument (a reference to the class instance). They work with attributes of a specific instance.

    class MyClass:
        def __init__(self, value):
            self.value = value
    
        def print_value(self):
            # Working with the instance attribute
            print(f"Value: {self.value}")
    
  2. Class Methods Take cls as the first argument (a reference to the class itself). Declared with the @classmethod decorator. They can be used as alternative constructors or to access class attributes.

    class MyClass:
        class_variable = "Class Data"
    
        @classmethod
        def print_class_variable(cls):
            # Working with the class attribute
            print(f"Class Variable: {cls.class_variable}")
    
        @classmethod
        def from_string(cls, data_string):
            # Alternative constructor
            value = int(data_string.split(":")[1])
            return cls(value)
    
  3. Static Methods Do not take self or cls. Declared with the @staticmethod decorator. They do not have access to instance or class attributes and are used to group related functions within a class where access to class or instance state is not needed.

    class MyClass:
        @staticmethod
        def helper_function(x, y):
            # Independent function conceptually related to the class
            return x + y
    
  4. Special Methods (Dunder Methods) Have names starting and ending with double underscores (e.g., __init__, __str__, __len__). Used to define class behavior with built-in functions and operators.

    class MyList:
        def __init__(self, items):
            self.items = items
    
        def __len__(self):
            # Defines behavior of len()
            return len(self.items)
    
        def __str__(self):
            # Defines string representation of the object
            return f"MyList with {len(self.items)} items"
    

Summary table:

Method Type First Argument Decorator Access to State Typical Purpose
Instance Method self No Instance Working with specific object data
Class Method cls @classmethod Class Alternative constructors, access to class attributes
Static Method None @staticmethod None Helper functions, independent of state
Special Method Depends on method No Instance/Class Overriding operations and built-in functions