[Python 🐍 Mastery] Python's Object-Oriented Programming Overview and Fundamentals ⭐️
Tags: beginners, python, programming, tutorial
Published: 2023-10-27 14:32:31

> 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/47l3gbdwsr6kordgjk8d.png)



## 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:
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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/tli93xefx0kvyemt8x70.png)

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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/3g9btfzwmbbxsczf052c.jpg)

{% cta https://zoom.us/webinar/register/WN_IxdNJcoWRjyqV3tvVHKByQ %}  Register for the AI Webinar ⚡️{% endcta %}

Also:
{% cta https://github.com/swirlai/swirl-search %}  Give ⭐ to Swirl {% endcta %}



## Coding a Class 💻

Here's a Chunky Class code:

```python

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](https://github.com/swirlai/swirl-search)



### Let's try to execute the code 🛠️

```python

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


![Code Execution](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xvsheqn7ml7fpgrlvxuw.png)



### Breaking down the code 🔍


I've added `__repr__` in my code. Why does your class need a `__repr__` method? 🤔

```python
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__`:**

![Without the __repr__](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/musl548cy1c4jnfa93lv.png)

**With the `__repr__`:**

![With the __repr__](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/0wl7vqd659qyldttm2w6.png)



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

{% cta https://github.com/swirlai/swirl-search %}  Give ⭐ to Swirl {% endcta %}

**Register for the AI Webinar & 3.0 Release**:

{% cta https://zoom.us/webinar/register/WN_IxdNJcoWRjyqV3tvVHKByQ %}  Register for the AI Webinar ⚡️{% endcta %}

Thanks for reading,
You all are breathtaking.

![You are breathtaking](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/kqhf5vqr2lj4z5kq4gdr.gif)