Methods within a class can be categorized into three main types:
Each type serves a different purpose and is used differently within a class. Here is an overview of each:
Instance methods are the most common type of method in a class. They operate on an instance of the class and can access and modify the attributes of the instance. These methods must include self
as the first parameter, which is a reference to the instance of the class.
class MyClass:
def __init__(self, value):
self.value = value
def instance_method(self):
return f'This is an instance method. Value: {self.value}'
# Creating an instance
obj = MyClass(10)
print(obj.instance_method()) # Output: This is an instance method. Value: 10
Class methods are methods that operate on the class itself rather than on instances of the class. They cannot modify instance-specific data but can modify class-level data. These methods use cls
as the first parameter, which is a reference to the class.
Class methods are defined using the @classmethod
decorator.
class MyClass:
class_variable = 'Class Variable'
@classmethod
def class_method(cls):
return f'This is a class method. {cls.class_variable}'
# Calling a class method
print(MyClass.class_method()) # Output: This is a class method. Class Variable
Static methods are similar to class methods, but they do not operate on the class or its instances. They do not take self
or cls
as the first parameter and cannot modify class or instance state. Static methods are utility functions that belong to the class but do not require access to class-specific data.
Static methods are defined using the @staticmethod
decorator.
class MyClass:
@staticmethod
def static_method(x, y):
return f'This is a static method. Sum: {x + y}'
# Calling a static method
print(MyClass.static_method(5, 7)) # Output: This is a static method. Sum: 12
self
as the first parameter.cls
as the first parameter and are marked with the @classmethod
decorator.self
or cls
and are marked with the @staticmethod
decorator.