Python Classes and Objects
What Are Classes and Objects?
A class is a user-defined blueprint or prototype from which objects are created. It defines attributes (variables) and methods (functions) that operate on the data.
- Class: A blueprint for creating objects (a template).
- Object: An instance of a class, containing data and behavior.
Syntax:
class ClassName:
# attributes and methodsCreate a class using the class keyword.
Example:
class Person:
first_name = "Dharmendra"
last_name = "Yadav"
age = 20Explanation:
Personis a class.first_name,last_nameandageare class attributes—they belong to the class, not any specific object
Creating an Object and Accessing Attributes
# Create an object of the Person class
p1 = Person()
# Access class attributes using the object
print("First Name:", p1.first_name)
print("Last Name:", p1.last_name)
print("Age:", p1.age)Output:
First Name: Dharmendra
Last Name: Yadav
Age: 20Class Attributes
If you want to use class attributes (shared across all objects), define them outside __init__
class Student:
school_name = "ABC Public School" # ✅ Class attribute
def __init__(self, id_number, name, age): # ✅ Correct constructor
self.id_number = id_number # Instance attributes
self.name = name
self.age = age
# Creating objects
s1 = Student(101, "Simran", 20)
s2 = Student(102, "Rahul", 22)
# Accessing instance and class attributes
print(s1.name, "-", s1.school_name)
print(s2.name, "-", s2.school_name)Output:
Simran - ABC Public School
Rahul - ABC Public SchoolExplanation:
school_nameis a class attribute, shared by allStudentobjects.id_number,name, andageare instance attributes, unique to each object.
Real-world example
Here's a real-world example using a MotorBike class — it includes both class attributes (shared by all bikes) and instance attributes (unique to each bike).
Example: MotorBike Class
class MotorBike:
# Class attribute
category = "Two Wheeler"
# Constructor
def __init__(self, brand, model, engine_capacity):
self.brand = brand # Instance attribute
self.model = model
self.engine_capacity = engine_capacity
# Instance method
def bike_info(self):
print(f"{self.brand} {self.model} - {self.engine_capacity}cc ({self.category})")Creating MotorBike Objects
bike1 = MotorBike("Honda", "Shine", 125)
bike2 = MotorBike("Yamaha", "R15", 155)
bike1.bike_info()
bike2.bike_info()Output:
Honda Shine - 125cc (Two Wheeler)
Yamaha R15 - 155cc (Two Wheeler)Explanation:
categoryis a class attribute (same for all bikes).brand,model,engine_capacityare instance attributes.bike_info()is a method that prints all the details of a bike.
What is an Object?
An object is an instance of a class. Think of a class as a template and an object as the real-world entity built using that template.
Example 1: Creating a Class and Object
class Person:
def __init__(self, name, age):
self.name = name # instance variable
self.age = age
def greet(self):
print(f"Hi, I’m {self.name} and I’m {self.age} years old.")
# Create object
p1 = Person("Alice", 25)
p1.greet()Output:
Hi, I’m Alice and I’m 25 years old.Explanation:
__init__()is a constructor, automatically called when the object is created.selfrefers to the current instance.greet()is a method that uses object attributes.
Example 2: Accessing and Modifying Attributes
print(p1.name) # Output: Alice
p1.age = 26 # Modify age
p1.greet() # Output reflects new ageExample 3: Class Variables vs Instance Variables
class Student:
school = "ABC School" # Class variable
def __init__(self, name):
self.name = name # Instance variable
s1 = Student("Tom")
s2 = Student("Jerry")
print(s1.school, s2.school)
s1.school = "XYZ School"
print(s1.school, s2.school)Output:
ABC School ABC School
XYZ School ABC SchoolExplanation:
- Class variables are shared.
- Instance variables are unique to each object.
s1.school = "XYZ School"creates a new instance variableschoolfors1.
Example 4: Inheritance
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal): # Inherits from Animal
def speak(self):
print("Dog barks")
d = Dog()
d.speak()Output:
Dog barksExplanation:
Doginherits fromAnimal.speak()method is overridden inDog.
Example 5: Using super()
class Animal:
def __init__(self, name):
self.name = name
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name) # Calls parent constructor
self.breed = breed
d = Dog("Rocky", "Labrador")
print(d.name, d.breed)Output:
Rocky LabradorExample 6: Encapsulation with Private Attributes
class Car:
def __init__(self, model):
self.__model = model # private variable
def get_model(self):
return self.__model
def set_model(self, model):
self.__model = model
c = Car("Toyota")
print(c.get_model()) # Access private attribute
c.set_model("Honda")
print(c.get_model())Output:
Toyota
HondaExample 7: Class Methods and Static Methods
class MathUtils:
count = 0
@classmethod
def increment(cls):
cls.count += 1
@staticmethod
def add(x, y):
return x + y
MathUtils.increment()
print(MathUtils.count) # 1
print(MathUtils.add(10, 5)) # 15Explanation:
@classmethodmodifies class state.@staticmethodbehaves like a regular function but within a class.
Summary Table
| Feature | Description | Example |
|---|---|---|
| Class | Template for creating objects | class Person: |
| Object | Instance of a class | p1 = Person("Tom", 20) |
__init__() | Constructor, initializes data | def __init__(self): |
self | Refers to current object | self.name = name |
| Inheritance | Derive from parent class | class Dog(Animal): |
super() | Calls parent methods | super().__init__() |
| Class vs Instance | Shared vs unique per object | self.name vs ClassName.school |
| Encapsulation | Hides internal variables | self.__speed |
| Classmethod | Acts on the class | @classmethod |
| Staticmethod | No class or instance needed | @staticmethod |