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.
An object is a specific instance of a class that has:
object_name = ClassName()
class Student:
name = "Rahul"
s1 = Student() # object creation
print(s1.name)
Output
Rahul
class Student:
def __init__(self, name):
self.name = name
s1 = Student("Rahul")
s2 = Student("Amit")
print(s1.name)
print(s2.name)
Output
Rahul
Amit
Objects can access:
class Student:
def __init__(self, name):
self.name = name
def display(self):
print("Name:", self.name)
s1 = Student("Rahul")
print(s1.name)
s1.display()
class Car:
def __init__(self, model):
self.model = model
car1 = Car("BMW")
car2 = Car("Audi")
print(car1.model)
print(car2.model)
Python provides the id() function to check the memory location of an object.
a = 10
b = 10
print(id(a))
print(id(b))
x = [1, 2, 3]
x.append(4)
x = 10
x = x + 5
| Class | Object |
|---|---|
| Blueprint | Instance |
| Logical entity | Physical entity |
| Defines structure | Uses structure |
Each student has: