Start learning free

LESSON 281 OF 673 · FUNCTIONS & CLASSES

Defining a Class in Python

Lesson

TL ; DR:

  • A class is a blueprint for creating objects. It groups together related data and behavior under a single name.


  • In Python, you define a class with the class keyword, followed by the class name, a colon, and an indented body:

    class Dog:
        pass
    

    The body must contain something — Python uses pass as a placeholder when there's nothing to do yet. We'll fill it in over the next lessons.



Full lesson:

So far, you've worked with built-in types like int, str, and lists. But what if you want to model something Python doesn't have a type for — like a Dog, a BankAccount, or a Game?

That's what classes are for. A class lets you define your own type by listing what data it holds and what actions it can perform.


Why classes?

Imagine you're writing a program about dogs. Each dog has a name, an age, and can bark. Without classes, you'd have to track each dog's name in one variable, age in another, and write a separate bark() function for each. That gets messy fast.

With a class, you bundle all of that into one neat package called Dog:

class Dog:
    pass   # We'll add attributes and methods in upcoming lessons.

The syntax

Defining an empty class in Python looks like this:

class ClassName:
    pass

Three things to notice:

  • The keyword class tells Python you're defining a new type.

  • ClassName is the name you choose. By convention, Python class names use PascalCase — capitalized words with no underscores: Dog, BankAccount, HighScore.

  • A colon ends the class header, and the body is indented below. Even an empty class needs something in its body — that's what pass is for: a do-nothing statement that's syntactically valid.


Your task

Define an empty class called Dog. The pre-filled code below will create an instance of your class and print a confirmation message. If you define the class correctly, the program will run and print:

Defined the Dog class!
STEP 1 OF 1
    Ctrl + Enter to check