Method Decorators in Python
Method decorators in Python are special decorators used inside classes to modify the behavior of
methods.
Here are some common method decorators:
1. @staticmethod
- Defines a method that doesn't access instance (self) or class (cls) data.
- Can be called using the class name or object.
Example:
class MyClass:
@staticmethod
def greet():
print("Hello from static method")
MyClass.greet()
2. @classmethod
- The method receives the class (cls) as the first argument.
- Used to create factory methods or access/modify class state.
Example:
class MyClass:
name = "Python"
@classmethod
def show_name(cls):
print(f"Class name is {cls.name}")
MyClass.show_name()
3. @property
- Makes a method act like an attribute (getter).
- Useful for read-only or computed properties.
Example:
class Circle:
def __init__(self, radius):
self._radius = radius
@property
def area(self):
return 3.14 * self._radius ** 2
c = Circle(5)
print(c.area)
Bonus: @<property>.setter
- Lets you set a value for a @property.
Example:
class Person:
def __init__(self, name):
self._name = name
@property
def name(self):
return self._name
@name.setter
def name(self, value):
self._name = value
p = Person("Alice")
p.name = "Bob"
print(p.name)
Summary Table:
| Decorator | Used for | Requires self or cls? |
|----------------|----------------------------------|------------------------|
| @staticmethod | Utility method (no self or cls) | No |
| @classmethod | Class-level logic (uses cls) | Yes, cls |
| @property | Read-only computed attribute | Yes, self |
| @property.setter| Make the property writable | Yes, self |