Last modified: Feb 10, 2026 By Alexander Williams
Python Objects: Classes, Instances, and Methods Guide
Python is an object-oriented programming language. This means everything in Python is an object. Understanding objects is key to writing powerful Python code.
An object is a bundle of data and functionality. It represents a real-world entity in your code. This guide explains Python objects for beginners.
What is a Python Object?
An object is an instance of a class. Think of a class as a blueprint. The object is the actual house built from that blueprint.
Every object has two main characteristics. It has attributes (data) and methods (functions). Attributes describe the object's state. Methods define its behavior.
Even simple data types are objects. An integer like `5` is an object of the `int` class. A string like `"hello"` is an object of the `str` class.
Creating a Class and Objects
You define a class using the class keyword. Inside, you define attributes and methods. The special __init__ method initializes new objects.
Let's create a simple `Car` class.
# Defining a simple Car class
class Car:
# The __init__ method is the constructor
def __init__(self, brand, model, year):
# These are instance attributes
self.brand = brand
self.model = model
self.year = year
self.mileage = 0 # Default attribute value
# This is an instance method
def drive(self, miles):
"""Increase the car's mileage."""
self.mileage += miles
print(f"The car has driven {miles} miles.")
# Another instance method
def get_info(self):
"""Return a formatted string with car info."""
return f"{self.year} {self.brand} {self.model} - Mileage: {self.mileage} mi"
The __init__ method runs when a new object is created. The `self` parameter refers to the instance being created. We assign values to `self.brand`, `self.model`, etc.
Now, let's create objects from this class. These objects are called instances.
# Creating instances (objects) of the Car class
my_car = Car("Toyota", "Camry", 2022)
friends_car = Car("Honda", "Civic", 2020)
print(my_car.get_info())
print(friends_car.get_info())
2022 Toyota Camry - Mileage: 0 mi
2020 Honda Civic - Mileage: 0 mi
We created two distinct `Car` objects. Each has its own data. Changing `my_car.mileage` does not affect `friends_car.mileage`.
Instance Attributes vs. Class Attributes
Attributes defined inside __init__ are instance attributes. They belong to a specific object. Class attributes are shared by all instances of the class.
class Dog:
# This is a CLASS ATTRIBUTE
species = "Canis familiaris"
def __init__(self, name, age):
# These are INSTANCE ATTRIBUTES
self.name = name
self.age = age
# Create two Dog objects
buddy = Dog("Buddy", 5)
max = Dog("Max", 3)
print(buddy.name, buddy.species) # Access instance and class attr
print(max.name, max.species)
# Changing a class attribute affects all instances
Dog.species = "Canis lupus"
print(buddy.species)
print(max.species)
Buddy Canis familiaris
Max Canis familiaris
Canis lupus
Canis lupus
Instance attributes are unique to each object. Class attributes are shared. They are useful for constants or default values common to all objects.
Working with Methods
Methods are functions defined inside a class. They operate on the object's data. The first parameter is always `self`. It gives the method access to the instance's attributes.
Let's add more functionality to our `Car` class.
class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
self.is_running = False
def start_engine(self):
"""Start the car's engine."""
if not self.is_running:
self.is_running = True
print(f"The {self.model}'s engine is now ON.")
else:
print(f"The {self.model}'s engine is already ON.")
def stop_engine(self):
"""Stop the car's engine."""
if self.is_running:
self.is_running = False
print(f"The {self.model}'s engine is now OFF.")
else:
print(f"The {self.model}'s engine is already OFF.")
# Using the methods
my_car = Car("Ford", "Mustang")
my_car.start_engine()
my_car.start_engine() # Trying to start it again
my_car.stop_engine()
The Mustang's engine is now ON.
The Mustang's engine is already ON.
The Mustang's engine is now OFF.
Methods encapsulate behavior related to the object. They make code organized and reusable.
The Importance of the Self Parameter
The `self` parameter is crucial. It is a reference to the current instance. Python passes it automatically when you call a method on an object.
It allows each object to maintain its own state. When `my_car.start_engine()` is called, `self` inside the method points to `my_car`.
Objects and Data Serialization
Often, you need to save an object's state or send it over a network. This process is called serialization. A common format is JSON.
However, Python objects are not directly JSON serializable. You need to convert them to a compatible format like a dictionary first. For a deep dive into this process, see our JSON Serialization Guide for Custom Python Objects.
Similarly, when you receive JSON data, you often want to convert it back into Python objects. The json.loads() function is the starting point for this. Learn more in our guide on Python JSON loads: Converting JSON to Python Objects.
Putting It All Together: A Practical Example
Let's build a more complete example. We will create a `BankAccount` class.
class BankAccount:
"""A simple class to represent a bank account."""
def __init__(self, account_holder, initial_balance=0):
self.account_holder = account_holder
self.balance = initial_balance
print(f"Account created for {self.account_holder}.")
def deposit(self, amount):
"""Deposit money into the account."""
if amount > 0:
self.balance += amount
print(f"Deposited ${amount}. New balance: ${self.balance}")
else:
print("Deposit amount must be positive.")
def withdraw(self, amount):
"""Withdraw money from the account."""
if 0 < amount <= self.balance:
self.balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.balance}")
else:
print("Invalid withdrawal amount or insufficient funds.")
def display_balance(self):
"""Display the current account balance."""
print(f"Account holder: {self.account_holder}")
print(f"Current balance: ${self.balance}")
# Create an account and use its methods
alice_account = BankAccount("Alice", 100)
alice_account.display_balance()
alice_account.deposit(50)
alice_account.withdraw(30)
alice_account.withdraw(200) # This should fail
Account created for Alice.
Account holder: Alice
Current balance: $100
Deposited $50. New balance: $150
Withdrew $30. New balance: $120
Invalid withdrawal amount or insufficient funds.
This example shows encapsulation. The `balance` data is protected. It can only be changed through the defined methods (`deposit`, `withdraw`). This prevents invalid states.
Conclusion
Python objects are the building blocks of object-oriented programming. A class is a blueprint. An object is an instance of that class.
Objects combine data (attributes) and behavior (methods). The `self` parameter connects methods to their specific instance. Understanding the difference between instance and class attributes is important.
Mastering objects leads to better code. Your programs become more modular, reusable, and easier to manage. Start by creating simple classes. Then, gradually add more features.
Remember, practice is key. Try creating classes for things around you. A `Book`, a `Student`, or a `Product` for an online store. This will solidify your understanding of Python objects.