In Python, a class method and an instance method are two different types of methods in a class:
.jpg)
- Instance Method: This type of method takes the instance (object) of a class as the first argument. It can access and modify the instance's data.
- Class Method: This type of method takes the class itself as the first argument. It can access and modify class-level data that is shared among all instances of the class.
Here's an example to illustrate the difference between the two types of methods:
class MyClass:
class_attr = 0 # class-level data
def __init__(self, instance_attr):
self.instance_attr = instance_attr # instance-level data
def instance_method(self):
print(f'Instance method called with {self.instance_attr}')
@classmethod
def class_method(cls):
print(f'Class method called with {cls.class_attr}')
# Creating instances of MyClass
obj1 = MyClass(1)
obj2 = MyClass(2)
# Calling instance method on instances of MyClass
obj1.instance_method() # Output: Instance method called with 1
obj2.instance_method() # Output: Instance method called with 2
# Calling class method on the class itself
MyClass.class_method() # Output: Class method called with 0
In the example above, instance_method is an instance method because it takes the self argument (i.e., the instance) and can access the instance-level attribute instance_attr. On the other hand, class_method is a class method because it takes the cls argument (i.e., the class) and can access the class-level attribute class_attr.
0 Comments