Cross_Column

Monday, 19 January 2026

Class and Object in Python




Class and Object in Python

In Python, Class and Object are the core building blocks of Object Oriented Programming (OOP). They help in organizing code, improving reusability, and modeling real-world entities.


What is a Class?

A class is a blueprint or template used to create objects. It defines:

  • Variables (called attributes)
  • Functions (called methods)

A class does not occupy memory until an object is created from it.

Syntax of a Class


class ClassName:
    # attributes
    # methods


Example of Class in Python


class Student:
    school_name = "ABC Public School"

    def study(self):
        print("Student is studying")

Explanation:

  • Student → Class name
  • school_name → Class variable
  • study() → Method
  • self → Refers to current object

What is an Object?

An object is a real instance of a class. It represents a real-world entity and occupies memory.

Multiple objects can be created from the same class.

Creating an Object


object_name = ClassName()


Example of Object in Python


s1 = Student()
s2 = Student()


s1.study()
print(s1.school_name)

Output:


Student is studying
ABC Public School


Using __init__() with Class and Object

The __init__() method is a constructor that initializes object data when an object is created.


class Employee:
    def __init__(self, name, salary):
        self.name = name
        self.salary = salary

    def display(self):
        print(self.name, self.salary)


emp1 = Employee("Chandan", 50000)
emp2 = Employee("Amit", 60000)

emp1.display()
emp2.display()


Difference Between Class and Object

Class Object
Blueprint or template Instance of a class
Does not occupy memory Occupies memory
Defines attributes and methods Uses attributes and methods
Declared once Can create multiple objects

Real-World Example

Class: Mobile Phone
Objects: iPhone, Samsung, OnePlus


class Mobile:
    def call(self):
        print("Calling...")

iphone = Mobile()
samsung = Mobile()

iphone.call()
samsung.call()


Class vs Object in Automation Testing


class LoginPage:
    def login(self):
        print("Login successful")

login_test = LoginPage()
login_test.login()

This approach is widely used in:

  • Selenium Page Object Model (POM)
  • Robot Framework libraries
  • Python test automation frameworks

Common Interview Questions

  • What is a class in Python?
  • What is an object?
  • Difference between class and object?
  • What is the role of self?
  • What is __init__()?

Conclusion

Understanding Class and Object is the foundation of Python OOP. Every advanced concept like inheritance, polymorphism, and abstraction depends on these two concepts.

👉 Learn more Python concepts with practical examples on way2testing.com

No comments:

Post a Comment

Few More

Multithreading and Multiprocessing in Python

Multithreading and Multiprocessing in Python Python provides powerful tools to perform multiple tasks simultaneously usi...