Skip to content

Python Classes and Objects

Updated 7 min read Aimerscrew

So far, you've stored data in variables, lists and dictionaries, and organized code with functions. Python classes and objects let you combine the two: you bundle data and the actions that work on that data into one neat package. This is the heart of object-oriented programming (OOP), and it's how most large Python programs, games and web apps are built. In this lesson, you'll create your first class, build objects from it, and give them attributes and methods.

🌍 Real-life example

A car factory has one blueprint for a model. The blueprint isn't a car; you can't drive it. But the factory uses it to build thousands of real cars. Every car follows the same design (four doors, an engine, a horn), yet each one has its own color, mileage and owner. Or think of a cookie cutter: one cutter, many cookies, and you can decorate each cookie differently. In Python, the blueprint or cutter is a class, and each car or cookie is an object.

What are classes and objects in Python?

A class is a blueprint that describes a kind of thing: what data it holds and what it can do. An object (also called an instance) is one specific thing created from that class.

  • Attributes are the data an object holds, like a car's color or brand. They're variables that belong to an object.
  • Methods are the actions an object can perform, like honk() or drive(). They're functions that belong to a class.
A Car class blueprint listing the attributes brand and color and the methods honk and describe, with arrows to three Car objects: a red Toyota, a white Tesla and a blue Ford
One class (the blueprint) can create many objects. Each object has the same methods but its own attribute values.

How do you create a class in Python?

Use the class keyword, a name, and a colon. Everything indented below belongs to the class. The smallest possible class uses pass as a placeholder body:

class Dog:
    pass

buddy = Dog()
luna = Dog()

print(type(buddy))
print(isinstance(luna, Dog))
<class '__main__.Dog'>
True

Writing Dog() with parentheses creates a new object. Here, buddy and luna are two separate Dog objects. The output __main__.Dog means "the class Dog defined in the file you're running". The built-in isinstance() function checks whether an object was made from a particular class.

💡 Tip

Class names use CapitalizedWords (often called PascalCase), like Dog, ShoppingCart or BankAccount. Variables and functions use snake_case. This makes it easy to tell at a glance that ShoppingCart() builds an object, while calculate_total() is a normal function call.

Adding attributes to objects

An object can store its own data. You reach an attribute with a dot: object.attribute. Each object keeps its own values, even when they come from the same class:

class Car:
    pass

my_car = Car()
my_car.brand = "Toyota"
my_car.color = "red"

your_car = Car()
your_car.brand = "Tesla"
your_car.color = "white"

print(my_car.brand, my_car.color)
print(your_car.brand, your_car.color)
Toyota red
Tesla white

Changing my_car.color has no effect on your_car. They're two different objects, just like two real cars from the same factory.

📝 Note

Setting attributes one by one after creating the object works, but it's repetitive and easy to forget one. In the next lesson, you'll learn the __init__ method, which sets up every attribute automatically when the object is created.

Adding methods to a class

A method is a function written inside a class. Every method gets the object it was called on as its first parameter, which by convention is named self. Through self, the method can read that object's attributes.

class Car:
    def honk(self):
        print("Beep beep!")

    def describe(self):
        print("This car is a", self.color, self.brand)

my_car = Car()
my_car.brand = "Toyota"
my_car.color = "red"

my_car.honk()
my_car.describe()
Beep beep!
This car is a red Toyota

When you write my_car.describe(), Python passes my_car into the method as self, so self.color means "this car's color". You don't pass self yourself; Python does it for you. You'll explore self in detail in the next lesson.

Methods can change an object's data

Objects really shine when their methods update their own attributes. Here's a step counter, like the one in a fitness watch. Each object remembers its own total between calls:

class StepCounter:
    def reset(self):
        self.steps = 0

    def walk(self, count):
        self.steps = self.steps + count

    def report(self):
        print("Steps today:", self.steps)

morning = StepCounter()
morning.reset()
morning.walk(1200)
morning.walk(800)
morning.report()

evening = StepCounter()
evening.reset()
evening.walk(3500)
evening.report()
Steps today: 2000
Steps today: 3500

The method walk() takes an extra argument, count, just like a normal function. The data (steps) and the actions (reset, walk, report) live together in one place.

You've been using objects all along

In Python, everything is an object. Strings, lists and numbers are all objects built from classes, and that's why they have methods you call with a dot:

greeting = "hello"
print(type(greeting))
print(greeting.upper())

playlist = ["Song A", "Song B"]
print(type(playlist))
playlist.append("Song C")
print(playlist)
<class 'str'>
HELLO
<class 'list'>
['Song A', 'Song B', 'Song C']

str and list are classes, greeting and playlist are objects, and upper() and append() are methods. Now you're learning to build your own classes in the same way.

Why use object-oriented programming?

You could store a car in a dictionary and write separate functions for it. That works for tiny programs, but classes scale much better:

BenefitWhat it means
OrganizationData and the code that uses it live together, so related things are easy to find.
ReuseWrite the class once, then create as many objects as you need.
Real-world modelingClasses map naturally to things like users, orders, products and players.
Fewer bugsEach object manages its own data, so one object can't accidentally overwrite another's.
GrowthFeatures like inheritance let you build new classes on top of existing ones.

Common mistakes with classes and objects

1. Forgetting the parentheses when creating an object

class Car:
    def honk(self):
        print("Beep beep!")

my_car = Car       # no parentheses: this is the class itself, not a new car
my_car.honk()
TypeError: Car.honk() missing 1 required positional argument: 'self'

Without (), my_car is just another name for the blueprint. Write my_car = Car() to build an actual object.

2. Forgetting self in a method

class Car:
    def honk():
        print("Beep beep!")

my_car = Car()
my_car.honk()
TypeError: Car.honk() takes 0 positional arguments but 1 was given

Python always passes the object into the method, so the method must have a parameter to receive it. Add self: def honk(self):.

3. Using an attribute that was never set

class Car:
    pass

my_car = Car()
my_car.brand = "Ford"
print(my_car.color)
AttributeError: 'Car' object has no attribute 'color'

An object only has the attributes you've given it. This is exactly the kind of mistake __init__ prevents, as you'll see next.

Practice exercise

🏋️ Try it yourself

Create a Book class with a method info() that prints the book's title and author, like Dune by Frank Herbert. Create two book objects, set a title and author on each, and call info() on both.

Show solution
class Book:
    def info(self):
        print(self.title, "by", self.author)

first = Book()
first.title = "Dune"
first.author = "Frank Herbert"

second = Book()
second.title = "Emma"
second.author = "Jane Austen"

first.info()
second.info()
Dune by Frank Herbert
Emma by Jane Austen

What's next?

You can now create classes, build objects and give them methods. Next, learn the Python __init__ method and self, the proper way to give every new object its starting data.

Key takeaways

  • A class is a blueprint; an object (instance) is one real thing built from it.
  • Create a class with the class keyword and an object by calling the class: my_car = Car().
  • Attributes are data stored on an object, accessed with a dot, like my_car.color.
  • Methods are functions defined inside a class; their first parameter is self, the object they were called on.
  • Each object keeps its own attribute values, so changing one object does not affect another.
  • Everything in Python is an object, including strings, lists and numbers.

Frequently asked questions

What is the difference between a class and an object in Python?

A class is the blueprint that describes what something has and can do. An object is a specific thing created from that blueprint. One class can create many objects, each with its own data.

How do you create an object in Python?

Call the class name with parentheses, like my_car = Car(). Each call creates a brand new, separate object.

What is an instance in Python?

Instance is another word for object. If buddy = Dog(), then buddy is an instance of the Dog class, and isinstance(buddy, Dog) returns True.

What is the difference between a method and a function?

A method is a function defined inside a class and called on an object with a dot, like car.honk(). Python automatically passes the object to the method as its first argument, self.

Is everything in Python an object?

Yes. Numbers, strings, lists, functions and even classes themselves are objects. That is why values like "hello" have methods such as upper().