In Python, there are three main types of methods that can be defined within a class: instance methods, class methods, and static methods. Here’s an overview of each type:
self
parameter as the first parameter, which refers to the instance of the class that the method is being called on. Instance methods can access and modify instance variables of the object. They are called on the object and can be used to perform specific operations on the data stored in the object.@classmethod
decorator and take the class as the first parameter instead of the instance. They can be used to modify class-level variables or perform operations that are not specific to a particular instance. Class methods are often used for creating alternate constructors, where you can create objects using different parameters than the default constructor.@staticmethod
decorator and do not take any special first parameter. They can be called on either the class or the instance and do not modify the class or instance state. They are typically used for utility functions that are related to the class but do not depend on the state of the object or the class.In this example, MyClass
defines three different types of methods:
instance_method
) which takes self
as its first parameter and can access instance variables of the object it is called on.class_method
) which takes cls
as its first parameter and can access class variables of the class it is called on.static_method
) which does not take any special first parameter and can be called on the class or an instance of the class, but cannot access any instance or class variables.class MyClass:
class_var = "class variable"
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def instance_method(self):
print("Instance method called")
print(f"arg1: {self.arg1}, arg2: {self.arg2}")
@classmethod
def class_method(cls):
print("Class method called")
print(f"class_var: {cls.class_var}")
@staticmethod
def static_method():
print("Static method called")
# Create an instance of MyClass
obj = MyClass("foo", "bar")
# Call the instance method
obj.instance_method()
# Call the class method
MyClass.class_method()
# Call the static method
MyClass.static_method()
Instance method called
arg1: foo, arg2: bar
Class method called
class_var: class variable
Static method called
This demonstrates how different types of methods can be defined in a class and called on instances or the class itself.