CodeBlanks Logo Icon CodeBlanks

Model design

Design the Post and Comment class skeleton.

Project: Blog app

In this five-lesson project you'll build a blog app. Each lesson adds one piece, and by the final lesson you'll complete a working mini command-line application.

You'll use what you learned in previous groups: classes, dataclasses and lists. Throughout the project you'll design a Post class that holds title, content and author. You'll add a Comment class and link comments to posts. Then a Blog class will let you add multiple posts and search through them.

Post and Comment skeleton

A post carries three core pieces of data: title, content and author. With the @dataclass decorator you define this class in a short form: each field name gets a type and an empty-string default.

A comment holds an author name and a short text. You define both classes separately; linking comments to posts is the next lesson. You'll also see field(default_factory=list) for an empty-list default.

Practice Define the Post and Comment classes

Write the first piece of this project. Define a Post class with the @dataclass decorator; include fields title: str = "", content: str = "" and author: str = "". Define a Comment class the same way with author: str = "" and text: str = "". Then create a post with p = Post(title="First post", content="Hello", author="Ayşe") and print its title with print(p.title).

Starter code

main.py
from dataclasses import dataclass, field

# Define the Post class: title, content, author fields
# Define the Comment class: author, text fields

# Create a Post instance and print its title

Sample solution

main.py
from dataclasses import dataclass, field

@dataclass
class Post:
    title: str = ""
    content: str = ""
    author: str = ""

@dataclass
class Comment:
    author: str = ""
    text: str = ""

p = Post(title="First post", content="Hello", author="Ayşe")
print(p.title)

Expected output

First post

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Why write a blog app with classes?

  • Post data and behavior stay in one unit; code is reusable. Correct answer
  • It can be written without classes, no difference.
  • Classes only work in projects with a database.
  • Using classes always slows the program down.

Explanation: A class bundles post data and behavior in one unit, so you can reuse the code in other projects.

2 Complete the type of the Post field

Question
@dataclass
class Post:
    title: ____ = ""
    content: str = ""
    author: str = ""
Answer
@dataclass
class Post:
    title: str = ""
    content: str = ""
    author: str = ""

Explanation: The title field is text, so the type is str.

3 Match the blog project concepts

Term Meaning
Post Holds post data
Comment Holds comment data
title Post title
author Post or comment writer

All lessons in Intermediate