class
- Python course
- Intermediate
- Lesson 1/116
- 5 min
Learn to define classes with class and __init__.
Defining a class
A class is a template used to create objects. In Python a class starts with the class keyword, followed by the class name, a colon and an indented body.
Example: class User:\n pass. Here User is the class name; pass fills an empty body. The class name must start with a letter; starting with an uppercase letter is a good habit. Defining a class does not run it; it only prepares the template.
Body and indentation
The class body is the indented area after the colon. In Python indentation is given with spaces; four spaces is common. If the body is empty, write pass; otherwise you get a SyntaxError.
Example: class Book:\n pass. Here the body holds only pass. Later we will add attributes and methods to the body. For now an empty body is enough.
Practice Define the User class
Define a class named User; its body should be pass. After the class, write print("User class defined").
Starter code
# Define the User classSample solution
# Define the User class
class User:
pass
print("User class defined")Expected output
User class defined
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which is a valid Python class definition?
- class User:\n pass Correct answer
- function User():\n pass
- User class:\n pass
- def class User:\n pass
Explanation: The class keyword, the class name and a colon lead into the indented body.
2 Complete the class definition
class Book____
pass
class Book:
pass
Explanation: The colon marks the start of the body.
3 Match the parts of a class
| Term | Meaning |
|---|---|
class |
Keyword |
Book |
Class name |
: |
Body start |