Sobes.tech
Junior — Middle

How does calling a class method differ from accessing an instance of that class?

sobes.tech AI

Answer from AI

In Python, calling a class method and calling an instance method differ in which object they are bound to and what parameters they receive.

  • Instance method — this is a regular method called through an object (an instance of the class). The first parameter is always self, which refers to the specific instance. Through self, you can access the attributes and other methods of this object.

  • Class method — this method is bound to the class itself, not to an instance. It is declared with the @classmethod decorator and takes cls as the first parameter — a reference to the class. Such methods can work with class attributes and create new instances.

Example:

class MyClass:
    class_var = 0

    def instance_method(self):
        print(f"This is an instance method, self: {self}")

    @classmethod
    def class_method(cls):
        print(f"This is a class method, cls: {cls}")

obj = MyClass()
obj.instance_method()  # Calling an instance method
MyClass.class_method() # Calling a class method

Thus, calling a class method does not require creating an instance, whereas an instance method works with a specific object.

How does calling a class method differ from accessing… - sobes.tech