Search⌘ K
AI Features

Introducing SocialNetwork (Composition)

Explore how to use composition to build a SocialNetwork class that manages User and Post objects together. Understand the benefits of organizing and scaling data centrally while creating modular and maintainable Python code.

Up until now, we’ve built our User and Post classes, and we’ve ensured that sensitive data is protected. But what happens when we scale up? Imagine managing a bustling social network where thousands of users post chirps daily. Without a central place to organize and manage all this data, your application would quickly become chaotic.

Until now, our User and Post classes have worked independently, handling their own data and behaviors. But in a real-world application, we need a home base to gather and manage these objects—a container that lets you easily search, update, and maintain everything in one place. This is where composition comes in.

Composition is an OOP concept where a class is built by combining objects of other classes. In composition, one class has objects of other classes as part of its internal structure. This ...

...
class SocialNetwork:
def __init__(self):
self.users = [ ] # This list will store User objects
self.posts = [ ] # This list will store Post objects
def add_user(self, user):
# Add a user object to the network
self.users.append(user)
print(user.display_name, "has been added to the network.")
def add_post(self, post):
# Add a post object to the network
self.posts.append(post)
print("A new post has been added to the network.")
SocialNetwork class

Composition in action

...