Notes

Object in Python [ English ]

< Prev Next >

1. Introduction

An object in Python is an instance of a class. It represents a real-world entity and contains data (attributes) and behavior (methods) defined by its class.

In simple terms:

A class is a blueprint, and an object is a real example created from that blueprint.

2. Definition of Object

An object is a specific instance of a class that has:

3. Creating an Object

Syntax

object_name = ClassName()

Example

class Student:
    name = "Rahul"

s1 = Student()   # object creation
print(s1.name)

Output

Rahul

4. Object with Constructor

class Student:
    def __init__(self, name):
        self.name = name

s1 = Student("Rahul")
s2 = Student("Amit")

print(s1.name)
print(s2.name)

Output

Rahul
Amit

5. Accessing Object Properties

Objects can access:

Example

class Student:
    def __init__(self, name):
        self.name = name

    def display(self):
        print("Name:", self.name)

s1 = Student("Rahul")

print(s1.name)
s1.display()

6. Multiple Objects

class Car:
    def __init__(self, model):
        self.model = model

car1 = Car("BMW")
car2 = Car("Audi")

print(car1.model)
print(car2.model)

7. Memory Concept

8. Object Identity

Python provides the id() function to check the memory location of an object.

a = 10
b = 10

print(id(a))
print(id(b))

9. Types of Objects

9.1 Mutable Objects

x = [1, 2, 3]
x.append(4)

9.2 Immutable Objects

x = 10
x = x + 5

10. Relationship Between Class and Object

Class Object
Blueprint Instance
Logical entity Physical entity
Defines structure Uses structure

11. Real-Life Example

Each student has:

12. Summary

< Prev Next >