Junior — Middle
Explain the differences between self and cls in the context of class methods.
sobes.tech AI
Answer from AI
In Python, self and cls are conventions for the first parameter of methods, but they serve different purposes:
selfis a reference to a specific instance of the class. It is used in instance methods to access attributes and methods of that object.clsis a reference to the class itself, not an instance. It is used in class methods (marked with the@classmethoddecorator) to work with the class as a whole, for example, to create new instances or modify class properties.
Example:
class MyClass:
class_var = 0
def __init__(self, value):
self.instance_var = value
def instance_method(self):
print(f'Instance var: {self.instance_var}')
@classmethod
def class_method(cls):
print(f'Class var: {cls.class_var}')
obj = MyClass(10)
obj.instance_method() # calls the instance method
MyClass.class_method() # calls the class method