OOP in Python - Cheat Sheet
1. Class and Object
A class is a blueprint, and an object is an instance of that class.
Example:
class Student:
def __init__(self, name):
self.name = name
s1 = Student('John')
print(s1.name)
2. Constructor (__init__)
The __init__ method is called when an object is created. Used to initialize variables.
3. self Keyword
'self' refers to the current instance of the class. It must be the first parameter in instance methods.
4. Inheritance
Inheritance allows a class to inherit methods and attributes from another class.
Example:
class Animal:
def speak(self):
print('Animal speaks')
OOP in Python - Cheat Sheet
class Dog(Animal):
pass
d = Dog()
d.speak()
5. Method Overriding
A child class can redefine a method from the parent class.
class Dog(Animal):
def speak(self):
print('Bark')
6. Encapsulation
Encapsulation means hiding the internal state using private variables.
Example:
class Bank:
def __init__(self):
self.__balance = 1000
def get_balance(self):
return self.__balance
7. Polymorphism
Same method name behaves differently for different classes.
OOP in Python - Cheat Sheet
Example:
class Cat:
def sound(self):
print('Meow')
class Dog:
def sound(self):
print('Bark')
def make_sound(animal):
animal.sound()
make_sound(Dog())
make_sound(Cat())