Python
Blog class
Set up collection management with the Blog class.
The Blog class manages the collection
Once you have a single Post instance, you need to collect them in a list. The Blog class does this: it holds an empty list named posts and adds new posts through an add_post method.
The line posts: list = field(default_factory=list) gives every new Blog instance its own empty list. Without default_factory=list, all instances would share the same list — a common bug.
The add_post method
The add_post method does one thing in a single line: self.posts.append(post). The self pseudo-variable refers to the instance itself, so the method can reach the posts list. To call it you write blog.add_post(Post(...)); the dataclass instance is ready in one line.
After adding, len(blog.posts) tells you how many posts the blog has. This count is what you'll print to confirm the add worked.
Exercise Write the Blog class and add_post method
The Post and Comment classes above are ready. Now define a Blog class with @dataclass; add the field posts: list = field(default_factory=list) and write def add_post(self, post): with the body self.posts.append(post). Then create blog = Blog(), add two posts and print the count with print(len(blog.posts)).
Show example solution
from dataclasses import dataclass, field
@dataclass
class Post:
title: str = ""
content: str = ""
author: str = ""
@dataclass
class Comment:
author: str = ""
text: str = ""
@dataclass
class Blog:
posts: list = field(default_factory=list)
def add_post(self, post):
self.posts.append(post)
blog = Blog()
blog.add_post(Post(title="First", author="Ayşe"))
blog.add_post(Post(title="Second", author="Ali"))
print(len(blog.posts))
Test yourself
-
Complete the default of the posts field
@dataclass
class Blog:
posts: list = field(default_factory=____)
def add_post(self, post):
self.posts.append(post)
Show answer
@dataclass
class Blog:
posts: list = field(default_factory=list)
def add_post(self, post):
self.posts.append(post)
-
What does default_factory=list do?
- Returns the list type
- Produces a fresh empty list for each instance
- Shares one list across the class
- Fills list items automatically
Show answer
Produces a fresh empty list for each instance — default_factory=list gives every new instance its own empty list, avoiding the shared-list bug.
-
Match the Blog class concepts
- posts
- Post list
- add_post
- Post-adding method
- len
- Count function
- self
- The instance itself
Next lesson: Adding comments