DEV Community

Cover image for [Python 🐍 Mastery] Python's Object-Oriented Programming Overview and Fundamentals ⭐️
Saurabh Rai for Swirl

Posted on

[Python 🐍 Mastery] Python's Object-Oriented Programming Overview and Fundamentals ⭐️

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.

Mountain Overview of Python


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:

  1. Must contain peanuts.
  2. Must have some oil in it.
  3. Crush the peanuts.
  4. Add some oil.
  5. Whip it.

The moment I follow these steps, a peanut butter is made.

Pythonic Peanut Butter

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:

Image description

Register for the AI Webinar ⚡️

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.")
        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!")
Enter fullscreen mode Exit fullscreen mode

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

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.connect_to_search_provider("Google PSE")"Why do you need __repr__ ?" )



Enter fullscreen mode Exit fullscreen mode

Now the output looks something like this:

Code Execution

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}>"
Enter fullscreen mode Exit fullscreen mode

Here's the same print(swirl_instance) without the __repr__:

Without the __repr__

With 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:

Give ⭐ to Swirl

Register for the AI Webinar & 3.0 Release:

Register for the AI Webinar ⚡️

Thanks for reading,
You all are breathtaking.

You are breathtaking

Top comments (7)

nathan_tarbert profile image
Nathan Tarbert

Good article @srbhr!

I'm currently diving more into Python, coming from a JavaScript background because of Python's handling capabilities.

srbhr profile image
Saurabh Rai

In the following article, let me show you how to create Linked Lists in Python.

srbhr profile image
Saurabh Rai

Yes, they both can be used to make amazing full-stack applications. JS for an awesome FE and Python for the Backend. Especially if you want to create some AI Applications out there.

rojblake1978 profile image

Great article. Thanks for posting it.

srbhr profile image
Saurabh Rai

You're welcome. I'm glad you liked it.

olivia73code profile image

Thank you for this blog, I am at the early stages of leaning Python, will definitely come back to this for further learning.

srbhr profile image
Saurabh Rai

I'm glad that you liked this blog post.