VOOZH about

URL: https://www.analyticsvidhya.com/blog/2021/08/python-tutorial-object-oriented-programming-system-oops-part-1/

โ‡ฑ Python Tutorial: Object-Oriented Programming system (OOPs) - Part 1


India's Most Futuristic AI Conference Is Back โ€“ Bigger, Sharper, Bolder

  • d
  • :
  • h
  • :
  • m
  • :
  • s

Python Tutorial: Object-Oriented Programming system (OOPs) โ€“ Part 1

Harika Last Updated : 12 Nov, 2024
7 min read
This article was published as a part of the Data Science Blogathon
In this article, we will try to help you understand/brush up on the basic OOP concepts.

Table of Contents:

  1. OOP and its importance
  2. Class, Instance/Object, __init__ method
  3. Creating Classes and Objects
  4. Accessing Attributes and Calling methods
  5. Variable Types
  6. Method Types

OOP and its importance

Object-oriented programming (OOP) is a notion that depends on the concept of objects. In OOP, objects are defined with their own set of attributes/properties.

It is important because it helps the developers in writing clean, modular code that can be reused throughout the development. . With modular coding, we get control of functions and modules.

It comes in handy primarily in the case of large application development.

Class, Instance/Object, __init__method

If you are a beginner, pay a good amount of time to understand the terminology explained below.

Class: It is a user-defined blueprint of an object with a predefined set of attributes common to all the objects.

Instance/Object: It is an individual entity that is created from a class.

__init__ method: __init__ method in OOP is nothing but a special function. Special functions are the functions that are used to enrich the class. These can be easily identified as they have double underscores on either side. __init__ method is used to initialize the attributes. It is called a constructor in other programming languages.

Creating Classes and Objects

Creating a class: The class statement creates a new class with a given ClassName.

๐Ÿ‘ creating class
Image by Author

The name of the class in Python follows Pascal Case. It is a naming convention where each word starts with a capital letter without any special characters used.

Initializing the attributes/variables: We are initializing the object with n attributes namely attr1, attr2,โ€ฆ., attrn.

Creating Methods: Method is nothing but a function with a set of rules based on which objects behave. Created two methods names method1, method2. Choose the method inputs based on the requirement. Here, method1 does not take any inputs other than the object. Whereas, method2 takes self.attr2 and does something to it.

Complete Syntax of creating a class:

class ClassName:




def __init__(self, attr1, attr2):

self.attr1 = attr1

self.attr2 = attr2




def method1(self):

pass




def method2(self, attr2):

pass


Example Class

Letโ€™s create a class that represents the authors at Analytics Vidhya. The main attributes of authors are their names and the number of articles that are published.

Then create two methods โ€“ one that prints the authorโ€™s details and another that updates the number of articles written by an author and are published.

class BlogathonAuthors:




def __init__(self, author_name, num_articles):

self.author_name = author_name

self.num_articles = num_articles

print("Created new author object")




def show(self):

"""This method prints the details of the author"""

print("In show method")

print(f"Author Name: {self.author_name}nNum of published articles: {self.num_articles}")




def update(self, num_articles):

"""This method updates the number of published articles"""

print("In update method")

self.num_articles = num_articles
 

Creating Instances/Objects:

The process of creating an instance or object from a class is called Instantiation. While creating an object, we should pass the arguments that are defined in the __init__ method.

Syntax: object = ClassName(arguments)

author1 = BlogathonAuthors("Harika", 10)

The above code creates an object named โ€œauthor1โ€ whose name is โ€œHarikaโ€ and has written 10 articles.

Similarly, we can create any number of objects required.

author2 = BlogathonAuthors("Joey", 23)

Accessing attributes and Calling methods

The syntax for accessing the attributes is object.attribute

The authorโ€™s name is accessed using author1.author_name, and the number of articles is accessed using author1.num_articles.

๐Ÿ‘ accessing attributes | Python Object-Oriented Programming

Rather than just displaying we can also change the values.

author1.num_articles = 9

Calling Methods: The two ways of calling methods are ClassName.method(object) or object.method()

Calling the show method to display the information about author1.

BlogathonAuthors.show(author1)
๐Ÿ‘ calling methods | Python Object-Oriented Programming

author1.show()

๐Ÿ‘ method calling

Wait, if you are familiar with functions in Python, you may get a doubt that the โ€œshowโ€ method accepts one argument but we didnโ€™t pass any.

Think of a minute about whatโ€™s happening here and continue reading further to know the answer.

show(self) method accepts one argument that is the object itself. The self keyword here points to the instance/object of the class. So when we call object.method(), it is nothing but we are passing the object as an argument.

Now, calling the update method and changing the number of articles.

author1.update(20)

After the update, if we see the details of author1, the number of articles will be 20.

๐Ÿ‘ calling update method | Python Object-Oriented Programming

Variable Types

The three different types of variables in OOP in Python are:

Instance Variables: Variables that are defined inside __init__ are called instance variables and these are of object level.

Class/Static Variables: Variables that are defined outside the __init__ method are called class variables and these are of class level.

Local variables: Variables that are confined to a method are called local variables and these are of method level.

To better understand the variables, create a variable that holds the type of authorsโ€™ work. All the blogathon authors are freelancers.

Also, let us create another method โ€œtotal_articlesโ€ that takes the number of articles drafted, and stores the sum of published, drafted articles to a variable called โ€œtotalโ€œ

so, here โ€œtypeโ€ is a class variable, and โ€œtotalโ€ is a local variable.

class BlogathonAuthors:
type ="freelancer"
def __init__(self, author_name, num_articles):
self.author_name = author_name
self.num_articles = num_articles
print("Created new author object")
def show(self):
"""This method prints the details of the author"""
print("In show method")
print(f"Author Name: {self.author_name}nNum of published articles: {self.num_articles}nType of Work: {BlogathonAuthors.type}")
def update(self, num_articles):
"""This method updates the number of published articles"""
print("In update method")
self.num_articles = num_articles
def total_articles(self, draft):
total = self.num_articles + draft
print(f"Total articles are: {total}")
 

Accessing class variables: can be accessed using ClassName.variable or object.variable

author3 = BlogathonAuthors("Karl", 3)
author3.type
๐Ÿ‘ class variable || Python Object-Oriented Programming

Accessing instance variables: object.variable

๐Ÿ‘ object variable

Accessing local variables:

Upon calling the total_articles function, it prints the total articles.

๐Ÿ‘ local variable | Python Object-Oriented Programming

But it throws an error if we try to access the โ€œtotalโ€ variable outside the total_articles method.

๐Ÿ‘ error

Method Types

The three types of Methods in OOP are:

  1. Instance methods
  2. Class methods
  3. Static methods

Instance methods: These are the methods used to get or set object attributes. These methods are also known as accessor methods (gets the details), mutator methods (sets the details). In our example, the โ€œshowโ€ method is the getter/accessor method and the โ€œupdateโ€ method is the setter/mutator method.

Class methods: To work with class/static variables we need to use the class methods.

Syntax: 

@classmethod 
def methodName(cls):
 # update staticvariable
 # return staticvariable

@classmethod is a decorator that is used to declare a class as a class method.

Static Methods: Any method that is neither related to class or object is a Static method.

Syntax:

@staticmethod 
def methodName():
 # code

@staticmethod is a decorator that is used to declare a method as a static method.

For example, letโ€™s add a class method to our existing class that returns the type of authorsโ€™ work, and a static method that prints some text.

class BlogathonAuthors:




type ="freelancer"




def __init__(self, author_name, num_articles):

self.author_name = author_name

self.num_articles = num_articles

print("Created new author object")




def show(self):

"""This method prints the details of the author"""

print("In show method")

print(f"Author Name: {self.author_name}nNum of published articles: {self.num_articles}nType of Work: {BlogathonAuthors.type}")




def update(self, num_articles):

"""This method updates the number of published articles"""

print("In update method")

self.num_articles = num_articles




def total_articles(self, draft):

total = self.num_articles + draft

print(f"Total articles are: {total}")




@classmethod

def return_type(cls):

return cls.type




@staticmethod

def stat_method():

print("I am a static method")
 

Calling Class method: ClassName.method()

BlogathonAuthors.return_type()
๐Ÿ‘ calling class method | Python Object-Oriented Programming

Calling Static method: ClassName.method()

BlogathonAuthors.stat_method()
๐Ÿ‘ calling stat method

End Notes:

Thank you for being patient till the conclusion. By the end of this article, we are familiar with the basic concepts of OOP in Python. Stay tuned to my next article on some other OOP concepts.

I hope this article is informative. Feel free to share it with your study buddies.

Other Blog Posts by me

Feel free to check out my other blog posts from my Analytics Vidhya Profile.

You can find me on LinkedIn, Twitter in case you would want to connect. I would be glad to connect with you.

For immediate exchange of thoughts, please write to me at [email protected].

Happy Learning!

The media shown in this article are not owned by Analytics Vidhya and are used at the Authorโ€™s discretion. 

Hi, my name is Harika. I am a Data Engineer and I thrive on creating innovative solutions and improving user experiences. My passion lies in leveraging data to drive innovation and create meaningful impact.

Login to continue reading and enjoy expert-curated content.

Free Courses

Generative AI - A Way of Life

Explore Generative AI for beginners: create text and images, use top AI tools, learn practical skills, and ethics.

Getting Started with Large Language Models

Master Large Language Models (LLMs) with this course, offering clear guidance in NLP and model training made simple.

Building LLM Applications using Prompt Engineering

This free course guides you on building LLM apps, mastering prompt engineering, and developing chatbots with enterprise data.

Improving Real World RAG Systems: Key Challenges & Practical Solutions

Explore practical solutions, advanced retrieval strategies, and agentic RAG systems to improve context, relevance, and accuracy in AI-driven applications.

Microsoft Excel: Formulas & Functions

Master MS Excel for data analysis with key formulas, functions, and LookUp tools in this comprehensive course.

Responses From Readers

Compliments to Harika! Well done and very clear explanations. Giaki - Italy

This article is very clean and to the point ..Thank you

Flagship Programs

GenAI Pinnacle Program| GenAI Pinnacle Plus Program| AI/ML BlackBelt Program| Agentic AI Pioneer Program

Free Courses

Generative AI| DeepSeek| OpenAI Agent SDK| LLM Applications using Prompt Engineering| DeepSeek from Scratch| Stability.AI| SSM & MAMBA| RAG Systems using LlamaIndex| Building LLMs for Code| Python| Microsoft Excel| Machine Learning| Deep Learning| Mastering Multimodal RAG| Introduction to Transformer Model| Bagging & Boosting| Loan Prediction| Time Series Forecasting| Tableau| Business Analytics| Vibe Coding in Windsurf| Model Deployment using FastAPI| Building Data Analyst AI Agent| Getting started with OpenAI o3-mini| Introduction to Transformers and Attention Mechanisms

Popular Categories

AI Agents| Generative AI| Prompt Engineering| Generative AI Application| News| Technical Guides| AI Tools| Interview Preparation| Research Papers| Success Stories| Quiz| Use Cases| Listicles

Generative AI Tools and Techniques

GANs| VAEs| Transformers| StyleGAN| Pix2Pix| Autoencoders| GPT| BERT| Word2Vec| LSTM| Attention Mechanisms| Diffusion Models| LLMs| SLMs| Encoder Decoder Models| Prompt Engineering| LangChain| LlamaIndex| RAG| Fine-tuning| LangChain AI Agent| Multimodal Models| RNNs| DCGAN| ProGAN| Text-to-Image Models| DDPM| Document Question Answering| Imagen| T5 (Text-to-Text Transfer Transformer)| Seq2seq Models| WaveNet| Attention Is All You Need (Transformer Architecture) | WindSurf| Cursor

Popular GenAI Models

Llama 4| Llama 3.1| GPT 4.5| GPT 4.1| GPT 4o| o3-mini| Sora| DeepSeek R1| DeepSeek V3| Janus Pro| Veo 2| Gemini 2.5 Pro| Gemini 2.0| Gemma 3| Claude Sonnet 3.7| Claude 3.5 Sonnet| Phi 4| Phi 3.5| Mistral Small 3.1| Mistral NeMo| Mistral-7b| Bedrock| Vertex AI| Qwen QwQ 32B| Qwen 2| Qwen 2.5 VL| Qwen Chat| Grok 3

AI Development Frameworks

n8n| LangChain| Agent SDK| A2A by Google| SmolAgents| LangGraph| CrewAI| Agno| LangFlow| AutoGen| LlamaIndex| Swarm| AutoGPT

Data Science Tools and Techniques

Python| R| SQL| Jupyter Notebooks| TensorFlow| Scikit-learn| PyTorch| Tableau| Apache Spark| Matplotlib| Seaborn| Pandas| Hadoop| Docker| Git| Keras| Apache Kafka| AWS| NLP| Random Forest| Computer Vision| Data Visualization| Data Exploration| Big Data| Common Machine Learning Algorithms| Machine Learning| Google Data Science Agent
๐Ÿ‘ Av Logo White

Continue your learning for FREE

Forgot your password?
๐Ÿ‘ Av Logo White

Enter OTP sent to

Edit

Wrong OTP.

Enter the OTP

Resend OTP

Resend OTP in 45s

๐Ÿ‘ Popup Banner
๐Ÿ‘ AI Popup Banner