Subjects

All subjects Django Java Python React Spring Boot JavaScript PHP
Sign Up Free
Interview question

What are common built-in decorators like @staticmethod, @classmethod, and @property? @staticmethod, @classmethod, @property जैसे common built-in decorators क्या हैं?

Answer
DecoratorFirst parameterCalled onPurpose
@staticmethodNone - no automatic self/clsClass or instanceUtility function logically grouped in the class
@classmethodcls (the class itself)Class or instanceAlternative constructors, class-level operations
@propertyselfInstance (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 या instanceClass में logically grouped utility
@classmethodclsClass या instanceAlternative constructors
@propertyselfInstance (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?