[Python 🐍 Mastery] Python's Object-Oriented Programming Overview and Fundamentals ⭐️
Saurabh Rai
Posted on October 27, 2023
Python is an easy-to-learn, powerful programming language.
~ Python 3.10 Tutorial
This will be a series that will cover Python. (Programming language, not the reptile, though both act the same way.)
Let's start with the basics, and we will work towards many Pythonic features.
This series aims to give you a mountain view of the Python Landscape. Take you on some valley trips and a trek alongside the river bank.
Classes
Object Oriented Programming (OOP) is popular. (Functional JavaScript Guys tend to disagree, I know.) But this is how we roll in Python. Let's dive deeper into the world of classes, objects, and OOP in Python.
What are Classes and Objects?
A class is a blueprint (that's what you've always heard of). Objects, on the other hand, are instances of classes. Think of a class as a prototype and an object as a specific item made from that prototype.
Let me simplify this: Classes are the abstract ideology that remains in your head or is like some instructions written in Python in a .py
file following the correct syntax.
And when you run that code, an object gets created. Objects are like real-world materialistic things.
- It takes up space (RAM)
- It takes computing power (runs on CPU)
So, a more straightforward example would be. I like peanut butter. I expect to make peanut butter this way:
- Must contain peanuts.
- Must have some oil in it.
- Crush the peanuts.
- Add some oil.
- Whip it.
The moment I follow these steps, a peanut butter is made.
Similarly, Classes are the blueprints that define something, and objects are the execution of those codes where Classes are written.
Swirling a bit 🌌
Yes, We're having a Webinar on How to use AI to create summaries of your data quickly and easily. And please come and watch our team release Swirl version 3.0, which will simplify the AI into your business (and projects) model.
Check it out & register:
Register for the AI Webinar ⚡️
Also:
Give ⭐ to Swirl
Coding a Class 💻
Here's a Chunky Class code:
class Swirl:
def __init__(self):
self.is_started = False
self.search_provider = None
self.search_results = []
self.ai_results = []
def __repr__(self):
return f"<Swirl: is_started={self.is_started}, search_provider={self.search_provider}>"
def search(self, query):
if not self.is_started:
print("Swirl is not started. Please start Swirl first.")
return
self.search_results = ["result1", "result2", "result3"]
print(f"Search results for '{query}': {self.search_results}")
def generate_ai_results(self, data):
self.ai_results = [f"AI processed: {item}" for item in data]
print(f"AI Results: {self.ai_results}")
def connect_to_search_provider(self, provider_name):
self.search_provider = provider_name
print(f"Connected to {provider_name} as search provider.")
def start(self):
self.is_started = True
print("Swirl has started!")
def stop(self):
self.is_started = False
self.search_provider = None
print("Swirl has stopped!")
Note: This is not how you write a search engine. There's a lot more stuff that goes into it. If you want to know more, check this GitHub Repository:github.com/swirlai/swirl-search
Let's try to execute the code 🛠️
# Making objects out of classes
swirl_instance = Swirl()
print(swirl_instance) # This will call the __repr__ method
swirl_instance.start()
swirl_instance.connect_to_search_provider("Google PSE")
swirl_instance.search("Why do you need __repr__ ?" )
swirl_instance.generate_ai_results(swirl_instance.search_results)
swirl_instance.stop()
Now the output looks something like this:
Breaking down the code 🔍
I've added __repr__
in my code. Why does your class need a __repr__
method? 🤔
def __repr__(self):
return f"<Swirl: is_started={self.is_started}, search_provider={self.search_provider}>"
Here's the same print(swirl_instance)
without the __repr__
:
With the __repr__
:
So, __repr__
provides an efficient object representation.
Instead of an arbitrary <__main__.Swirl object at 0x102870910>
we get the message that we want. It's really helpful for debugging and logging important things.
We also have a method called __str__
as well. (More on it and comparisons in a later article.)
Also, there's an __init__
innit?
Yes, that code initialises initial variables (attributes) and kick-starts a Python class. It's an initialiser method.
The self
parameter in the __init__
method refers to the instance being created. It's a convention to name this parameter self
, though technically, you could name it anything. You can replace that with this
as well. (For the JS Devs 😂).
And the rest are functions that perform their tasks altogether. They're called Methods if they are in a class. (Developers like to keep things simple and silly.)
Dunder Struck ⚡️
You've seen methods (functions) like:
__init__
__repr__
And more:
__str__
__del__
__iter__
These methods are called "Dunder" methods, short for "double underscore" methods, and are special methods in Python that have double underscores at the beginning and end of their names. They allow developers to customise built-in Python behaviours for user-defined objects.
Next Steps ⏭️
So, you've got the outlook of:
- Classes
- Objects
- Methods
- Attributes
- Dunder Methods
In the next blog (or article), let's use it to create a Linked List and reverse it in Python.
I've heard that the market is rising, and there will be more jobs. So let's do data structures and some advanced Python and be ready to apply to the next Generative AI company 💖.
Heads up 🌸
Okay, let you know. Swirl is also a company that creates a search platform and uses it to perform federated searches. It's a metasearch engine.
The Release of version 3.0 is coming, and it will allow you to search multiple databases and sources of information and generate AI summaries from it with sources and references. (Basically Retrieval Augmented Generation).
Check our:
GitHub Repository and book-mark it by:
Register for the AI Webinar & 3.0 Release:
Register for the AI Webinar ⚡️
Thanks for reading,
You all are breathtaking.
Posted on October 27, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.