Back to Blog

Python Decorators, @classmethod & @property Explained. #23

Sandy LaneSandy Lane

Video: Python Decorators, @classmethod & @property Explained. #23 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Python Decorators, @classmethod & @property Explained

This tutorial dives into Python decorators and class-related decorators like @classmethod, @staticmethod, and @property. You will learn how to write and apply decorators, use class methods as alternative constructors, and manage attribute access with properties, all demonstrated through clear, practical examples.

Code

def debug(func):
  # A simple decorator to print function call details
  def wrapper(*args, **kwargs):
    print(f"Calling {func.__name__} with args={args}, kwargs={kwargs}")
    result = func(*args, **kwargs)
    print(f"{func.__name__} returned {result}")
    return result
  return wrapper

class User:
  def __init__(self, username, email):
    self._username = username
    self._email = email

  @classmethod
  def from_string(cls, user_str):
    # Alternative constructor parsing "username,email"
    username, email = user_str.split(",")
    return cls(username, email)

  @staticmethod
  def is_valid_email(email):
    # Simple email validation
    return "@" in email and "." in email

  @property
  def email(self):
    # Getter for email attribute
    return self._email

  @email.setter
  def email(self, value):
    # Setter with validation
    if not self.is_valid_email(value):
      raise ValueError("Invalid email address")
    self._email = value

  @debug
  def greet(self):
    return f"Hello, {self._username}!"

# Usage examples:
user1 = User("alice", "alice@example.com")
print(user1.greet())

user2 = User.from_string("bob,bob@example.com")
print(user2.greet())

try:
  user2.email = "invalid-email"
except ValueError as e:
  print(e)

Key Points

  • Decorators like @debug wrap functions to add behavior before and after calls.
  • @classmethod defines alternative constructors that receive the class as the first argument.
  • @staticmethod defines utility methods that do not access instance or class data.
  • @property allows controlled access to attributes with optional setter validation.
  • Stacking decorators and combining them with classes enables clean, maintainable code.