In Python, there are three types of methods in a class: instance methods, class methods, and static methods. Let’s explore the differences between class methods and instance methods:
- Instance Method:
- An instance method is the most common type of method in Python classes. It takes the instance (
self
) as its first parameter and can access and modify the instance state.
- An instance method is the most common type of method in Python classes. It takes the instance (
class MyClass:
def instance_method(self):
print("This is an instance method")
# Create an instance and call the instance method
obj = MyClass()
obj.instance_method()
2. New-Style Class Method (Alternative Terminology):
class MyClass:
class_variable = "I am a class variable"
@classmethod
def class_method(cls):
print("This is a class method")
print(cls.class_variable)
# Call the class method on the class
MyClass.class_method()
In summary, instance methods are associated with the instance of the class and can access instance-specific data, class methods are associated with the class and can access and modify class-level data, and new-style class method is just another term for a class method in the context of Python 3 and new-style classes.