Junior — Middle
Can you name popular built-in decorators in Python and give examples of their use?
sobes.tech AI
Answer from AI
In Python, there are several popular built-in decorators:
@staticmethod— converts a class method into a static method that does not take theselfparameter.@classmethod— a method that receives the class as the first argument instead of an instance.@property— allows accessing a method as an attribute, implementing getters and setters.
Examples:
class MyClass:
@staticmethod
def static_method():
print("This is a static method")
@classmethod
def class_method(cls):
print(f"This is a class method {cls}")
def __init__(self):
self._value = 0
@property
def value(self):
return self._value
@value.setter
def value(self, new_value):
self._value = new_value
obj = MyClass()
MyClass.static_method() # call static method
MyClass.class_method() # call class method
obj.value = 10 # use property
print(obj.value) # output 10