PYTHON

Building Basic Data Models with Python Classes

Learn to define custom Python classes for representing web entities like users or products, enabling structured data handling and object-oriented programming practices in your backend.

class User:
    """
    A simple class to represent a user in a web application.
    """
    def __init__(self, user_id, username, email, is_active=True):
        self.user_id = user_id
        self.username = username
        self.email = email
        self.is_active = is_active

    def __repr__(self):
        # A developer-friendly representation
        return f"User(id={self.user_id}, username='{self.username}', active={self.is_active})"

    def __str__(self):
        # A user-friendly string representation
        return f"{self.username} <{self.email}>"

    def deactivate(self):
        """Marks the user as inactive."""
        if self.is_active:
            self.is_active = False
            print(f"User {self.username} deactivated.")
        else:
            print(f"User {self.username} is already inactive.")

    def to_dict(self):
        """Converts the User object to a dictionary (useful for JSON serialization)."""
        return {
            "id": self.user_id,
            "username": self.username,
            "email": self.email,
            "is_active": self.is_active
        }

# Create user instances
user1 = User(1, "alice", "[email protected]")
user2 = User(2, "bob", "[email protected]", is_active=False)

print(user1)          # Uses __str__
print(repr(user2))    # Uses __repr__

user1.deactivate()
user2.deactivate()

# Convert to dictionary for API response
user_data_json = user1.to_dict()
print(f"User 1 as dict: {user_data_json}")
How it works: Custom Python classes are fundamental data structures for modeling entities within a web application, such as users, products, or orders. They encapsulate data (attributes) and behavior (methods) related to that entity. This snippet demonstrates defining a `User` class with an initializer, string representations (`__str__`, `__repr__`), a method to change state, and a method to convert the object into a dictionary, which is essential for serialization into formats like JSON for API responses.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs