Interview question
What are class methods and static methods? Class methods और static methods क्या हैं?
Answer
| Type | Decorator | Receives | Use Case |
|---|---|---|---|
| Instance | @property | self | Instance data |
| Class Method | @classmethod | cls | Class data |
| Static Method | @staticmethod | None | Utility functions |
class MyClass:
class_var = 0
def __init__(self, value):
self.value = value
MyClass.class_var += 1
# Instance method
def instance_method(self):
return f'Value: {self.value}'
# Class method
@classmethod
def from_string(cls, string):
value = int(string)
return cls(value)
@classmethod
def get_count(cls):
return cls.class_var
# Static method
@staticmethod
def is_positive(num):
return num > 0
@staticmethod
def multiply(a, b):
return a * b
# Using class method
obj = MyClass.from_string('10')
print(MyClass.get_count()) # 1
# Using static method
print(MyClass.is_positive(5)) # True
print(MyClass.multiply(3, 4)) # 12
# Static method - no access to self or cls
class Math:
@staticmethod
def add(a, b):
return a + b
@staticmethod
def subtract(a, b):
return a - b
print(Math.add(5, 3)) # 8
print(Math.subtract(5, 3)) # 2# Instance method - self
def method(self):
return self.value
# Class method - cls
@classmethod
def class_method(cls):
return cls.class_var
# Static method - no self/cls
@staticmethod
def static_method(a, b):
return a + bWas this answer clear?