Course contentsShow
← Python
Lesson 410 of 1,0607. Object-Oriented ProgrammingFree lesson

Defining Classes with the Class Keyword

Learners will define basic class structures to serve as blueprints for creating custom data types in Python applications.

In this lesson, you will learn how to create your own custom data types by defining blueprints with the class keyword.

What is a Class?

Until now, you’ve used built-in types like dictionaries, lists, and strings to hold data. Sometimes, however, your application needs a specific "shape" of data—like a User, Product, or SensorReading—that carries its own properties. A class acts as a blueprint. It doesn’t hold actual data itself; rather, it tells Python what that data structure should look like when you create an object from it.

Defining Your First Class

To define a class, we use the class keyword followed by a name (conventionally using PascalCase). Inside the block, we define what the object is. For now, we will create a simple structure to hold attributes.

class Robot:
    pass

# Creating an instance (an object) of the Robot class
my_robot = Robot()

# We can assign attributes to this specific instance
my_robot.name = "Sparky"
my_robot.battery_level = 100

Why Use Classes?

When you define a class, you are creating a custom blueprint. While we can manually attach attributes to an object like shown above, classes are the foundation for building complex, reusable code. By defining a class, you signal to your program (and other developers) that any object created from this blueprint will follow a predictable structure.

This approach is much cleaner than using generic dictionaries. Instead of remembering that a dictionary needs a key called "battery_level", you use an object where that property is a known part of its identity. As we progress, we will see how these blueprints can also store functions (methods) to change the state of the objects they create.

For now, remember that class Robot: simply creates a new type in your application. You are essentially teaching Python a new concept, allowing you to organize your data into logical, named entities rather than relying solely on built-in types.

Key Takeaway: The class keyword allows you to define a custom blueprint that serves as the foundation for creating your own unique data types in Python.