Creating Classes

Python

Your First Class

Classes and Objects

A class is a blueprint for creating objects. An object is an instance of a class.

Basic Class Structure

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

Create an object

my_dog = Dog("Buddy", 3) print(my_dog.name) # Buddy

Key Concepts

  • __init__ is the constructor method
  • self refers to the current instance
  • Attributes store data about the object

    Your Task

    Create a class called Expense with:

  • An __init__ method that takes description and amount
  • Store both as instance attributes

    Create an expense and print its description and amount.

  • Code Editor
    Loading PYTHON engine...
    Loading...
    Loading Python engine...

    Run your code to see output