Class & Objects In Python. Topic – 40

Class & Objects In Python

Class & Objects In Python

Introduction Of Class:

Class is like a blueprint, that helps to create objects. Every object represents the different types of data. Class is like a template, that helps us to create objects.

Why We Should Use Class:

We use class to organize complex code structurally. The class makes the code modular, so we can reuse these codes. By defining a class, we can create multiple objects from it, which have different behaviors and properties.

Syntex Of Class:

    class ClassName:
        # Attributes (characteristics/properties)
        variable1 = value1
        variable2 = value2

        # Methods (functions/actions)
        def method1(self, parameters):
            # Code for method1

        def method2(self, parameters):
            # Code for method2

Keynotes Of Class:

  • We can declare the class using the ‘class’ keywords.
  • We can define variables and multiple functions in the class.
  • The self parameter provides a reference to the object of the class, through which we can access the variables and methods inside the class.

What is ‘self’:

Self is a parameter that represents each instance of a class. When we call a method of a class, So Python passes that instance of itself as the first parameter and refers to it as self. You can technically have any named parameter, but using self makes the code easier to read and understand.

We can create a method in the class. It will help you to create more features in the class. The method takes a ‘self’ keyword in the parameter. Let’s understand through an example:

class Students:
    name = 'arpan' #'arpan' default value
    age = 22
    doing  = 'programming'

    def data(self):
        print(f"{} is a student and age is {self.age}")

a = Students()

#update the object = 'shivam'

a.age = 20

a.doing = 'coding'

#create another object
b = Students() = 'priti'

b.age = 24

b.doing = 'software developer'

The Output Of This Code Will Be:

arpan is a student and age is 22 
shivam is a student and age is 20
software developer
priti is a student and age is 24

Now time to go to the next step. In this step, we will create another class that will be more advanced and usually used in our real-life program. Let’s see:

class Students:
    def __init__(self, name, roll, dept): = name
        self.roll = roll
        self.dept = dept
    def display(self):
        print(f"name: {} roll: {self.roll} dept: {self.dept}")

# Creating objects of class Students
st1 = Students("Shivam", 18, "developer")
st2 = Students("Rina", 21, "desiginer")
st3 = Students("Priti", 22, "HR")
# Accessing and displaying through the method

The Output Of This Code Will Be:

name: Shivam roll: 18 dept: developer
name: Rina roll: 21 dept: desiginer
name: Priti roll: 22 dept: HR  

After doing this program, a big question must arise in your mind: what does __init__ do? Where did this come from?

What is __init__?

__init__ is a special method that is used to initialize the objects of every class. The full form of __init__ is “initialize”. When we create an object of a class, the __init__ method is automatically called. If you want to know about __init__ then read this post [Click On Me]

What Is An Object?

The object is the entity of the program, that stores the data, and performs some specific task with the data. Let’s see another example of class for more clarification:

class Product:
    def __init__(self, name, price, stock): = name
        self.price = price
        self.stock = stock

    def display_info(self):
        print(f"Product: {}\nPrice: ${self.price}\nStock: {self.stock} units\n")

# Creating objects of class Product
product1 = Product("Laptop", 800, 10)
product2 = Product("Headphones", 50, 50)

# Accessing and displaying product information

The Output Of This Code Will Be:

Product: Laptop
Price: ₹800    
Stock: 10 units

Product: Headphones
Price: ₹50
Stock: 50 units  

Now try to write a program without class:

# Function to calculate the area of a rectangle

def calculate_rectangle_area(length, width):
    return length * width

# Function to display rectangle information
def display_rectangle_info(length, width):
    area = calculate_rectangle_area(length, width)
    print(f"Rectangle Information:\nLength: {length}\nWidth: {width}\nArea: {area}\n")

# Using functions
rectangle1_length = 5
rectangle1_width = 3
display_rectangle_info(rectangle1_length, rectangle1_width)

rectangle2_length = 7
rectangle2_width = 4
display_rectangle_info(rectangle2_length, rectangle2_width)

The Output Of This Code Will Be:

Rectangle Information:
Length: 5
Width: 3
Area: 15

Rectangle Information:
Length: 7
Width: 4

Ohhhooo! How much pain to write a simple program? Now see how we can write this same program using class:

class Rectangle:
    def __init__(self, length, width):
        self.length = length
        self.width = width

    def calculate_area(self):
        return self.length * self.width

    def display_info(self):
        area = self.calculate_area()
        print(f"Rectangle Information:\nLength: {self.length}\nWidth: {self.width}\nArea: {area}\n")

# Using class
rectangle1 = Rectangle(5, 3)

rectangle2 = Rectangle(7, 4)

The Output Of This Code Will Be:

Rectangle Information:
Length: 5
Width: 3
Area: 15

Rectangle Information:
Length: 7
Width: 4
Area: 28

Advantages of Using The Class:

  • Class-based code is often more readable and organized. In the class-based example, the logic related to rectangles is encapsulated within the class, making it self-contained.
  • Code Reusability:
  • With a class, you can easily create multiple instances (objects) with different attributes. This promotes code reusability and modularity.
  • Object-Oriented Approach:
  • Class-based programming follows an object-oriented approach, providing a natural and intuitive way to model and organize code.
  • Encapsulation:
  • Class-based code allows you to encapsulate data and methods within the class, reducing the chances of unintended interference with other parts of the code

Example For Practice Class & Objects

Simple Questions:

  1. Question: Rectangle Class Create a Python class Rectangle with attributes length and width. Include methods to calculate the area and perimeter of the rectangle. Create an instance of the class, set values for length and width, and display the area and perimeter.
  2. Question: Student Class Design a Python class Student with attributes name, roll_number, and marks. Include a method to display the student information. Create two instances of the class with different information and display their details.
  3. Question: Bank Account Class Implement a Python class BankAccount with attributes account_number and balance. Include methods to deposit and withdraw money from the account. Create an instance of the class, perform a few transactions, and display the final balance.

Tricky Questions:

  1. Question: Inheritance Create a base class Shape with a method area(). Derive two classes Rectangle and Circle from Shape with their own area() methods. Create instances of both derived classes and display their areas.
  2. Question: Class Methods and Variables Implement a Python class Dog with a class variable species set to “Canis familiaris.” Include a class method to change the species. Create two instances of the class, display their species, change the species using the class method, and display the updated species.
Introduction to OOPs In Python

Introduction to OOPs in Python

In this post, we will give an introduction to OOPs in Python. Object Oriented Programming is the concept of writing…

I hope you understand “Class & Objects in Python. Need guidance or have questions? Drop a comment below. Share your email for a personalized touch—I’ll send exclusive resources and answer queries. Let’s code together, creating efficient code and memorable learning moments! 🚀

Finite number of  lines code and infinite possibilities

Programmer, Arpan Bera

Leave a Reply

Your email address will not be published. Required fields are marked *

Arpan Bera

Coding is like Love – everyone can start, but only a few finish without errors

Keep Updated to our News and Blog