Popular
Data Science
Technology
Finance
Management
Future Tech
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.
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:
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.
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:
Output:
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.
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 .
Output:
In this example:
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.
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.
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:
In this example, make, model, and year are attributes. We can easily access and modify them to reflect changes.
Also Read: Python Functions
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:
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.
Let’s build something more complex—a Library that manages a collection of Book objects.
Output:
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.
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:
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:
This method checks for provided values and updates the object’s attributes accordingly.
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.
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.
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.
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.
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:
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.
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.
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.
The DevOps Playbook
Simplify deployment with Docker containers.
Streamline development with modern practices.
Enhance efficiency with automated workflows.
Popular
Data Science
Technology
Finance
Management
Future Tech
Accelerator Program in Business Analytics & Data Science
Integrated Program in Data Science, AI and ML
Certificate Program in Full Stack Development with Specialization for Web and Mobile
Certificate Program in DevOps and Cloud Engineering
Certificate Program in Application Development
Certificate Program in Cybersecurity Essentials & Risk Assessment
Integrated Program in Finance and Financial Technologies
Certificate Program in Financial Analysis, Valuation and Risk Management
© 2024 Hero Vired. All rights reserved