CBSE Class 12 Core Topic: Classes, objects, inheritance, polymorphism, encapsulation.
// Class Definition
class Student:
def __init__(self, name, roll):
self.name = name
self.roll = roll
def display(self):
print(f"Name: {self.name}, Roll: {self.roll}")
student1 = Student("Raj", 101)
student1.display()
// Constructor (__init__)
Special method called when object created
Initialize instance variables
Can take parameters
// Instance vs Class Variables
class Employee:
company = "TechCorp" # Class variable (shared)
def __init__(self, name, salary):
self.name = name # Instance variable
self.salary = salary
emp1 = Employee("Priya", 50000)
emp1.name # Access instance variable
Employee.company # Access class variable
// Inheritance (Reuse code from parent)
class Person:
def __init__(self, name):
self.name = name
def greet(self):
return f"Hello, {self.name}"
class Student(Person): # Inherits from Person
def __init__(self, name, roll):
super().__init__(name) # Call parent constructor
self.roll = roll
s = Student("Amit", 102)
s.greet() # Inherited method
// Polymorphism (Many forms)
Different classes, same method name
class Dog:
def sound(self):
return "Woof!"
class Cat:
def sound(self):
return "Meow!"
def make_sound(animal):
print(animal.sound())
make_sound(Dog()) # Woof!
make_sound(Cat()) # Meow!
// Encapsulation (Hide internal details)
Use private variables with __ prefix
class Account:
def __init__(self, balance):
self.__balance = balance # Private
def deposit(self, amount):
self.__balance += amount
def get_balance(self):
return self.__balance
account = Account(1000)
account.deposit(500)
balance = account.get_balance() # Safe access
// String Methods Review
str.upper(), lower(), capitalize()
str.replace(old, new)
str.split(separator), str.join(list)
str.strip() # Remove whitespace
str.find(substring), str.count(substring)
str.startswith(), str.endswith()