Classes and Objects in Python

Classes and Objects in Python

7 mins read732 Views Comment
clickHere
Updated on Jul 4, 2022 17:19 IST

This article includes classes and objects in python. This is very important topic from interview point of view.

2022_07_cc.jpg

There are two types of programming languages – procedure-oriented and object-oriented. Major emphasis is on functions in the former type, whereas in the latter languages, we focus on objects as the main entities. Python is an object-oriented programming (OOP) language where we extensively use objects that belong to a particular class. In a sense, the class explains the object. In this article, we will focus on classes and objects in python

Let’s understand with an example: We have a building prototype containing details about its floors, square foot area, etc. Based on this prototype, the building is constructed. So, the prototype is our class, and the building is its object.

This article will give you a basic understanding of classes and objects in Python. We will be covering the following sections:

What is an Object in Python?

A Python object is a collection of data (aka variables) and methods (aka functions) that act on the data. An object is also referred to as an instance of a class. 

Let’s recall the example we discussed above, shall we? You know many buildings can be constructed from a given prototype. Similarly, one can create multiple objects from a class. Creating the objects or instances of a class is known as instantiation. 

A class object in Python has the following properties:

  • State: data (variables) of the object
  • Behavior: methods (functions) of the object
  • Identity: unique name of the object

What is a Class in Python?

A class is a user-defined blueprint for creating an object. Python classes possess attribute information on how to create an object as well as how to interact with those objects –

  • Data attributes: required to create an object (instance).
  • Procedural attributes: provide methods (functions) that could be used to interact with and modify the instances. 
How to Find the Factorial of a Number Using Python
How to Find the Factorial of a Number Using Python
In this article, we will discuss different methods to find the factorial of a number in python using for, while, ternary operator and math module.
How to Generate Random Numbers in Python?
How to Generate Random Numbers in Python?
In Data Science or Statistics, there are various instances where a programmer might need to work with random inputs. Python offers many predefined functions to generate and use random data....read more
Python Split() Function for Strings
Python Split() Function for Strings
The below article goes through explaining and implementing split function in python with suitable examples.

Built-in Classes in Python

Since the advent of Python 3, the terms class and type for native Python objects are identical –

  • Several data type classes are offered in Python, such as integer, float, string, boolean, list, tuple, set, dictionary, range, and so on.
a = 7.33
b = 'This is a String'
c = [1, 2, 3, 'List']
d = True
e = (1, 2, 3, 'Tuple')
f = range(5)
 
for var in [a, b, c, d, e, f]:
    print(var.__class__)
 
<Class 'float'>
<Class 'str'>
<Class 'list'>
<Class 'bool'>
<Class 'tuple'>
<Class 'range'>
  • Python functions, whether built-in or user-defined, have their own classes/types:
def myfunction():
    pass
 
print(myfunction.__class__)
print(min.__class__)
 
<Class 'function'>
<Class 'builtin_function_or_method">
  • When working with Python libraries, you can create objects of the classes/types related only to those libraries:
import pandas as pd
import numpy as np
 
s = pd.Series({'x': 1, 'y': 2})
df = pd.DataFrame(s)
arr = np.array([1, 2, 3, 4])
 
print(s.__class__)
print(df.__class__)
print(arr.__class__)

Output
<Class 'pandas.core.series.Series'>
<Class 'pandas.core.frame.Daataframe'>
<Class 'numpy.ndarray'>

Apart from the built-in classes, we can also create our own classes depending on our requirements. Let’s see how:

 Creating a Python Class

In Python, we generally create a class using the class keyword, followed by the name of the class. Let’s take an example –

The following code creates a class named Blog:

class Blog():
  def __init__(self, name, publisher, wordlength):
    self.name = name
    self.publisher = publisher
    self.wordlength = wordlength
 

 The __init__ function

The __init__ function defined above is called the class constructor. This special function is automatically called when an instance (object) of the class is created. It is used to initialize the class variables. 

As shown above, any function in Python is defined using the keyword def. The arguments of the __init__ function represent the data attributes of the class: 

  • The argument self refers to the newly created instance itself. Every time a class instance calls one of its methods, the instance itself is passed as the first parameter. You can name this first argument whatever you want, but it is advisable to call itself for ease of understanding.
  • We can add additional parameters as shown above. In this case, we have specified the name, publisher, and wordlength to create an instance of the class Blog.

Now, let’s create an instance of this class, shall we?

 Creating a Python Object

We can create new objects that can be used to access the attributes of the class Blog, as shown in the following example:

b1 = Blog("Python", "Shiksha Online", 1669)
print(type(b1))
 
Output
<Class '__main__.Blog'>
 
 

Here, b1 is the object that belongs to the class Blog. To confirm this, we have used the type() function to return the object type.

Accessing and modifying the attributes of a class object:

#Accessing the name attribute
print(b1.name)
 
Output
Python
 
 
#Modifying the name attribute
b1.name = 'Classes in Python'
print(b1.name)
 
Output
Classes in Python
 
 

Creating and deleting the attributes of a class object:

#Creating an attribute
b1.writer = 'Jane Doe'
print(b1.writer)
 
Output
Jane Doe
 
 
#Deleting the writer attribute
del writer
print(b1.writer)
 
Output
NameError:name 'writer' is not defined
 

As demonstrated, we can use the del statement to delete an attribute. We created and then deleted the writer attribute here, so when we try printing it after deletion, it throws a NameError.

Defining procedural attributes of a class:

Right now, the class Blog has only data attributes. We can add procedural attributes, or methods (functions), to our class to improve its functionality.

For example, let’s implement a method that returns the number of pages if the font size is specified. We had already mentioned the word length of the Blog when we created the b1 object. Now, we will define a class method to calculate the number of pages based on the number of words and font size:

def pages(self, fontsize=13):
  wordlength = self.wordlength
 
  if fontsize == 13:
    words_per_page = 300
  else:
    words_per_page = 300 - (fontsize - 13) * 10
 
  total_pages = wordlength / words_per_page
  return round(total_pages)
     
 

We have defined a function called pages and specified the fontsize as a parameter. This function will calculate the total number of blog pages based on the wordlength and fontsize.

Once we have declared the function inside the class definition, we will access the data attributes of the object by telling the function how to do it: 

wordlength = self.wordlength

Now, we can access the function from the class Blog or its object b1. Let’s see how:

  • Using the class to call the function:
Blog.pages(b1)
Output
6
  • Using the object to call the function:
b1.pages()
Output
6

We can explicitly mention the font size as it is passed as an argument to the pages() function. Let’s see what happens if we increase the font size:

b1.pages(fontsize=24)
Output
9

So, if the font size is increased, the total number of pages increases too – which makes sense!

Class and Object Variables

Class variables:

These are declared inside a class but outside of any function. These are general variables that can be applied to almost all of the objects of a class.

Object variables: 

These are declared inside the __init__ function. These variables are more specific and are defined for each object separately. 

Let’s consider the class Blog we created above. Each Blog has a set style standard – such as page width and color of the text. Such attributes can be defined as class variables, so we do not need to declare them for each new object created explicitly.

The variables page_width and text_color are inside the class definition but outside of any function, as shown:

class Blog():
  page_width = 14
  text_color = "black"
  def __init__(self, name, publisher, wordlength):
    self.name = name
    self.publisher = publisher
    self.wordlength = wordlength
 

 You can modify a class variable for a particular instance. Let’s consider the example below where we have created a new object b2: 

b2 = Blog("Machine Learning", "Shiksha Online", 21338)
 
b2.text_color = 'blue'
 
print(b2.text_color)
 
Output
blue
 

However, modifications on a particular instance will not affect the class variable in general: 

print(Blog.text_color)
 
Output
blue
 

Endnotes

I hope this article was helpful for you to understand how to work with classes and objects in Python. We learned about the different types of built-in Python classes and how to create a new class. We how to access, modify, create, and delete class attributes. We also discussed how to instantiate a class and object in python and differentiate between class and object variables. Classes are a broad topic in Python. Once you are comfortable working with the basics, feel free to move on to the more advanced topics. Want to learn more about Python and practice Python programming? Explore related articles here.

About the Author

This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio

Comments