Python for AIPython for AI
Python Basics

Classes

Create your own data types

Python's classes let you build complex programs by organizing your code into reusable blueprints for data and functions. This is a very powerful concept!

What is object-oriented programming?

Object-oriented programming, or OOP, is a way of writing code. It helps you manage complexity. You create "objects" that combine data and the actions that can be performed on that data.

Think of it like real-world objects. A car has properties (color, model) and actions (drive, brake). In OOP, your code objects work similarly.

What is a class?

A class is like a blueprint or a template for creating objects. It defines the common properties and behaviors that all objects of that type will have.

When you create an object from a class, that object is called an "instance" of the class. Each instance is a unique copy based on the same blueprint.

python
class Dog:
    def __init__(self, name, breed):
        self.name = name
        self.breed = breed

    def bark(self):
        return f"{self.name} says Woof!"

# Creating instances (objects) from the Dog class
my_dog = Dog("Buddy", "Golden Retriever")
your_dog = Dog("Lucy", "Poodle")

In this example, Dog is the class. my_dog and your_dog are instances of the Dog class.

Why use classes?

Classes help you organize your code. They make your programs clearer and easier to understand, especially as they grow larger.

  • Reusability: Write code once in a class, then create many objects from it.
  • Modularity: Break down complex problems into smaller, manageable pieces (classes).
  • Maintainability: Changes to one part of your program are less likely to break others.

Classes allow you to create your own custom data types. Instead of just numbers or strings, you can have Dog objects, Car objects, or BankAccount objects, each with their own specific data and actions.

python
print(my_dog.name)
print(your_dog.breed)
print(my_dog.bark())

Practice

Try these exercises to lock in what you just learned.

Quiz
Not started
A class is best described as…