Introducing SocialNetwork (Composition)
Learn what composition is.
We'll cover the following...
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 forms a has-a relationship—if a
SocialNetworkclass has users and posts, thenSocialNetworkis composed of these objects within a single organization.
class SocialNetwork:def __init__(self):self.users = [ ] # This list will store User objectsself.posts = [ ] # This list will store Post objectsdef add_user(self, user):# Add a user object to the networkself.users.append(user)print(user.display_name, "has been added to the network.")def add_post(self, post):# Add a post object to the networkself.posts.append(post)print("A new post has been added to the network.")