Blog class
- Python course
- Intermediate
- Lesson 60/116
- 6 min
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.
Practice 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)).
Starter code
from dataclasses import dataclass, field
@dataclass
class Post:
title: str = ""
content: str = ""
author: str = ""
@dataclass
class Comment:
author: str = ""
text: str = ""
# Define the Blog class: posts list and add_post method
# Create a blog, add two posts, print the countSample 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))Expected output
2
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the default of the posts field
@dataclass
class Blog:
posts: list = field(default_factory=____)
def add_post(self, post):
self.posts.append(post)
@dataclass
class Blog:
posts: list = field(default_factory=list)
def add_post(self, post):
self.posts.append(post)
Explanation: default_factory=list gives each instance its own empty list.
2 What does default_factory=list do?
- Returns the list type
- Produces a fresh empty list for each instance Correct answer
- Shares one list across the class
- Fills list items automatically
Explanation: default_factory=list gives every new instance its own empty list, avoiding the shared-list bug.
3 Match the Blog class concepts
| Term | Meaning |
|---|---|
posts |
Post list |
add_post |
Post-adding method |
len |
Count function |
self |
The instance itself |