Interview question
What are common built-in decorators like @staticmethod, @classmethod, and @property? @staticmethod, @classmethod, @property जैसे common built-in decorators क्या हैं?
Answer
| Decorator | First parameter | Called on | Purpose |
|---|---|---|---|
| @staticmethod | None - no automatic self/cls | Class or instance | Utility function logically grouped in the class |
| @classmethod | cls (the class itself) | Class or instance | Alternative constructors, class-level operations |
| @property | self | Instance (accessed like an attribute) | Computed/read-only attributes |
class Pizza:
def __init__(self, radius, toppings):
self.radius = radius
self.toppings = toppings
# Regular instance method - needs self, operates on instance data
def area(self):
return 3.14159 * self.radius ** 2
# staticmethod - no access to self or cls, just grouped logically here
@staticmethod
def is_valid_topping(topping):
return topping in ['cheese', 'pepperoni', 'mushroom']
# classmethod - alternative constructor pattern
@classmethod
def margherita(cls):
return cls(radius=12, toppings=['cheese', 'tomato'])
# property - accessed like an attribute, computed on the fly
@property
def diameter(self):
return self.radius * 2
pizza = Pizza(10, ['cheese'])
print(pizza.area()) # instance method - needs ()
print(Pizza.is_valid_topping('cheese')) # static - called on class directly
margherita = Pizza.margherita() # classmethod - alternative constructor
print(margherita.toppings) # ['cheese', 'tomato']
print(pizza.diameter) # property - NO parentheses, accessed like attribute| Decorator | पहला parameter | कैसे call होता है | उद्देश्य |
|---|---|---|---|
| @staticmethod | कोई नहीं | Class या instance | Class में logically grouped utility |
| @classmethod | cls | Class या instance | Alternative constructors |
| @property | self | Instance (attribute की तरह) | Computed/read-only attributes |
class Pizza:
def __init__(self, radius, toppings):
self.radius = radius
self.toppings = toppings
def area(self):
return 3.14159 * self.radius ** 2
@staticmethod
def is_valid_topping(topping):
return topping in ['cheese', 'pepperoni', 'mushroom']
@classmethod
def margherita(cls):
return cls(radius=12, toppings=['cheese', 'tomato'])
@property
def diameter(self):
return self.radius * 2
pizza = Pizza(10, ['cheese'])
print(pizza.area())
print(Pizza.is_valid_topping('cheese'))
margherita = Pizza.margherita()
print(margherita.toppings)
print(pizza.diameter) # parentheses नहीं, attribute की तरहWas this answer clear?