Blog header background

What is Object in Python? A Comprehensive Guide

Updated on August 27, 2024

12 min read

Copy link
Share on WhatsApp

Python is the language that most of us choose when we need to solve problems quickly and efficiently. But have any of you ever stopped to think: How does Python organise all those extremely varied types of data that we deal with?

The secret lies in Python being object-oriented.

Python is not just about writing code that works; it’s about writing code that makes sense. Objects are at the heart of this. They’re the reason why Python feels so intuitive once you get the hang of it.

Say you’re putting together a bookshelf. You don’t want your books to be scattered all over the floor, correct? You want them to be arranged neatly, maybe by genre or author.

Well, Python does the same thing to your data by organising them into what is referred to as objects. Doing so makes the code not only neat and tidy but also manageable, more so when it grows:

So, what is object in Python, and why should you care? Let us break it down.

Defining an Object in Python and Its Core Properties

In Python, an object is like a box that contains a small amount of data and the methods necessary to work with that data. You can think of it as a little program within your program.

Every object in Python has three core properties:

  1. State (Attributes): These are the data inside the box. Suppose we have an object representing a car; then, in this case, attributes would refer to the colour, model, and mileage of the car.
  2. Behaviour (Methods): These are the things that the object can do. In Python, they are functions; however, we call them methods if they belong to an object.
  3. Identity: Though an object may look identical to another, every object is different. Python uses this identity to distinguish one object from another.

For example, even if you have two cars that look exactly alike, they will still be different. Their identity is represented as a memory address in the code, and that’s how Python keeps track of objects.

brochure-banner-bg

POSTGRADUATE PROGRAM IN

Multi Cloud Architecture & DevOps

Master cloud architecture, DevOps practices, and automation to build scalable, resilient systems.

Understanding Object Identity, State, and Behaviour in Python

Let’s break down these concepts with a real-life example.

Suppose that you have a class named Smartphone in Python. Now, each smartphone would have some other features, like brand, model, and battery_life, which would point out the state of the object.

Now, every smartphone can do things like ‘make_call’, ‘send_message’, or ‘browse_internet’. These actions are behaviours or methods of the object.

Even if you had two smartphones of the same brand and model, for Python, they were two different objects with different identities. That can come in very handy because it will allow us to manage those two objects one by one, even if they look the same.

Here’s a quick Python code snippet to illustrate:

class Smartphone:

def __init__(self, brand, model, battery_life):

self.brand = brand

self.model = model

self.battery_life = battery_life
 

def make_call(self, number):

print(f"Calling {number} from {self.brand} {self.model}")
 

# Create two smartphone objects

phone1 = Smartphone("BrandA", "ModelX", "10 hours")

phone2 = Smartphone("BrandA", "ModelX", "10 hours")
 

# They may look the same but are different objects

print(id(phone1))

print(id(phone2))

Output:

137658548202384

137658548203792

Here, phone1 and phone2 might have the same state and behaviour, but they’re distinct objects, each with its unique identity.

The id() function in Python shows us this by printing out a unique identifier for each object.

How to Create and Instantiate Objects in Python

Now that we understand what an object is, how do we create one?

In Python, we create objects from classes. A class is like a blueprint. It defines what the objects created from it will look like and how they will behave.

To build an object, we simply call the class, passing in any necessary information, and Python does the rest.

Let’s say we want to create a Book class. Each book will have a title, author name, and year of publication .

class Book:
def __init__(self, title, author, year):

self.title = title

self.author = author

self.year = year

 

def book_info(self):

return f"'{self.title}' by {self.author}, published in {self.year}"

 

# Instantiate objects from the Book class

book1 = Book("1984", "George Orwell", 1949)

book2 = Book("To Kill a Mockingbird", "Harper Lee", 1960)

 

# Display information about the books

print(book1.book_info())

print(book2.book_info())

Output:

'1984' by George Orwell, published in 1949

'To Kill a Mockingbird' by Harper Lee, published in 1960

In this example:

  • The Book class is our blueprint.
  • The __init__ method is a special method in Python that initialises the object’s state. It runs automatically when we create a new object.
  • The book_info method provides a summary of the book.

If we create book1 and book2, then we are creating two different objects, book1 with its title, author and year of publication whereas book2 also has a title, author and the year of publication.

The objects’ identities and functions are handled by Python, and even though they are of the same class, they operate independently.

Exploring Object Attributes, Methods, and the Role of __init__()

When diving into Python, understanding how to handle data and perform actions is key. But how does Python know what data to use or what actions to take?

The answer lies in attributes and methods.

What Are Object Attributes?

Attributes are the data inside an object. They describe the object and hold values that define its current state.

Think of attributes as the characteristics of an object.

Let’s consider a Car object. What makes one car different from another? It could be the colour, model, or year it was made. These characteristics are attributes in Python.

Here’s how we define them in code:

class Car:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

 

# Creating a Car object

my_car = Car("Toyota", "Corolla", 2020)

 

# Accessing attributes

print(my_car.make)  # Output: Toyota

print(my_car.model) # Output: Corolla

print(my_car.year)  # Output: 2020

In this example, make, model, and year are attributes. We can easily access and modify them to reflect changes.

Also Read: Python Functions

What Are Object Methods?

If attributes are the “what” of an object, methods are the “how”. Methods are functions belonging to an object. They define what an object can do.   Methods are actions that objects can perform. They interact with the object’s attributes or other methods to produce a result.   Continuing with the Car example, driving, honking, or braking would be methods.   Let’s see how we can define and use methods:

class Car:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year 

def start_engine(self):

print(f"The {self.model} engine has started.") 

def stop_engine(self):

print(f"The {self.model} engine has stopped.") 

# Creating a Car object

my_car = Car("Toyota", "Corolla", 2020) 

# Using methods

my_car.start_engine()  # Output: The Corolla engine has started.

my_car.stop_engine()   # Output: The Corolla engine has stopped.

The Role of __init__() in Objects

The __init__() method is special in Python. It’s the initialiser, automatically called when a new object is created. It sets up the initial state by assigning values to the object’s attributes.   Think of __init__() as the setup instructions that run every time we create a new object.   In the Car example above, __init__() is used to set the make, model, and year every time we create a new car. Without __init__(), our objects would be empty shells with no data.

skill-test-section-bg

82.9%

of professionals don't believe their degree can help them get ahead at work.

Detailed Example: Creating a Custom Class with Objects in Python

Let’s build something more complex—a Library that manages a collection of Book objects.

class Book:

def __init__(self, title, author, year):

self.title = title

self.author = author

self.year = year

 

def get_info(self):

return f"'{self.title}' by {self.author}, published in {self.year}"

 

class Library:

def __init__(self):

self.books = []

 

def add_book(self, book):

self.books.append(book)

print(f"Book '{book.title}' added to the library.")

 

def remove_book(self, title):

for book in self.books:

if book.title == title:

self.books.remove(book)

print(f"Book '{title}' removed from the library.")

return

print(f"Book '{title}' not found in the library.")

 

def display_books(self):

if not self.books:

print("No books in the library.")

else:

for book in self.books:

print(book.get_info())

 

# Creating Library and Book objects

library = Library()

 

book1 = Book("1984", "George Orwell", 1949)

book2 = Book("To Kill a Mockingbird", "Harper Lee", 1960)

 

library.add_book(book1)

library.add_book(book2)

 

# Displaying books

library.display_books()

 

# Removing a book

library.remove_book("1984")

library.display_books()

Output:

Book '1984' added to the library.

Book 'To Kill a Mockingbird' added to the library.

'1984' by George Orwell, published in 1949

'To Kill a Mockingbird' by Harper Lee, published in 1960

Book '1984' removed from the library.

'To Kill a Mockingbird' by Harper Lee, published in 1960

This example shows how we can manage a collection of objects using methods to add, remove, and display books. The Library class demonstrates how objects interact with each other.

Accessing and Modifying Object Properties and Methods

After creating objects, we often need to update or retrieve their attributes. Python allows us to access and modify attributes easily.   Let’s say we want to change the year of a Book in our Library:

book1.year = 1950

print(book1.get_info())  # Output: '1984' by George Orwell, published in 1950

Here, we directly modify the year attribute of book1.

But what if we want to add a new method to update multiple attributes at once? We can do that, too:

class Book:

def update_info(self, title=None, author=None, year=None):

if title:

self.title = title

if author:

self.author = author

if year:

self.year = year

print(f"Book information updated to '{self.title}' by {self.author}, published in {self.year}")

 

# Updating book information

book1.update_info(year=1984)

This method checks for provided values and updates the object’s attributes accordingly.

Advanced Features: __str__() Method and Custom String Representation

The __str__() method in Python has the ability to control how a particular object is going to be represented as a string.   It empowers us to produce what will be printed when we use print() on a certain object. It is good for the enhancement of the readability of an object. This comes in handy, especially when we would like to print an object to the console and get a meaningful output that is easily interpretable rather than getting a confusing memory address.

class Book:

def __init__(self, title, author, year):

self.title = title

self.author = author

self.year = year 

def __str__(self):

return f"'{self.title}' by {self.author} ({self.year})" 

# Creating a Book object

book = Book("The Catcher in the Rye", "J.D. Salinger", 1951) 

# Printing the book object

print(book)  # Output: 'The Catcher in the Rye' by J.D. Salinger (1951)

Deleting Object Properties and Objects in Python

Sometimes, it is necessary to delete a specific portion of our code. Perhaps it is no longer as valuable, or maybe an entire object is no longer of any use. How would this be done in Python?   Deleting both properties and objects in Python is possible. It is like rearranging a shelf where one has to remove the clutter.

Removing Object Properties

Let’s say we have a Car object, and we no longer need to keep track of its model. We can remove that attribute with a single command.

class Car:

def __init__(self, make, model, year):

self.make = make

self.model = model

self.year = year

 

# Create a Car object

my_car = Car("Toyota", "Corolla", 2020)

 

# Delete the model attribute

del my_car.model

 

# Try to access the deleted attribute

try:

print(my_car.model)

except AttributeError:

print("Model attribute has been deleted.")

In this example, we use the del keyword to remove the model attribute. If we try to access my_car.model afterward, Python raises an AttributeError.   This tells us that the attribute no longer exists.

Deleting Objects

Sometimes, we need to remove the object completely. It can occur when the object is no longer useful or when we’re cleaning up resources in our code.   Deleting an object is, again, quite simple. We use the del keyword, but this time, we apply it to the object itself:

# Delete the entire object

del my_car 

# Try to access the deleted object

try:

print(my_car)

except NameError:

print("The my_car object has been deleted.")

Here, del my_car completely removes the my_car object.   Trying to access my_car afterward results in a NameError, indicating that the object no longer exists in memory.

Common Misconceptions about Objects in Python

Misconception 1: Deleting an Object Frees Up Memory Immediately

When we delete an object, it doesn’t instantly free up memory. Python uses a system called garbage collection to manage memory.   The object is marked for deletion, and Python clears it up later.

Misconception 2: The __init__() Method Is the Only Way to Define the Object’s Attributes Apart from __init__(), there is more than one way of setting attributes. We can also set them directly or set them after the object has been created.

Misconception 3: Objects Are Copied When Passed to a Function

Python passes the objects by references and not by values, as is the case with many other languages. What this means is that the original object is changed by changes made within the function and not a copy.

Conclusion

Understanding how to manipulate, create, edit, and even delete objects is the core concept of Python programming.

One has to admit that objects help to make the code more structured and, therefore, easier to read. They are good in a way that allows us to depict real-life objects in a manner that would be understandable to our programs.

To be able to manage the objects’ data and behaviour effectively, we first need to know about attributes and methods. Objects provide us with the ability to construct complex and highly versatile applications ranging from establishing details for a car and all the way to organising a library of books.

This knowledge allows a developer to write clean Python code, avoid pitfalls, and make their code easier to maintain and scale.

FAQs
How to create many objects from the same class in Python?
We can create several objects by calling the class with different arguments. These objects will have their own set of attributes and methods.
Can objects in Python be deleted? If so, how?
Yes, objects can be deleted by using the del keyword. This removes a reference to the object, so the object is then collected as garbage.
What is the difference between a class and an object in Python?
A class is a blueprint or template defining the structure and behaviour of objects. An object is, hence, one of the instances of a class that holds a particular example with its own data.
Why is the self-parameter necessary in Python methods?
The self-parameter enables each method to access the attributes and methods of the object to which it belongs. It's how the method knows whose data to work with.
What is the purpose of the __str__() method in a Python class?
The __str__() method controls how an object is represented as a string, usually when it needs to be printed. It is used to give a readable and meaningful string representation of the object.

Updated on August 27, 2024

Link
Loading related articles...