Python OOP Cheat Sheet
1. Basic Class & Object
-----------------------
class Player:
def __init__(self, name, sport):
self.name = name
self.sport = sport
def introduce(self):
print(f"I am {self.name} and I play {self.sport}")
p1 = Player("Vignesh", "Cricket")
p1.introduce()
2. The self Keyword
--------------------
- Refers to the current instance of the class
- Required in all instance methods
3. Instance vs Class Variables
-------------------------------
class Team:
team_type = "Sports" # class variable
def __init__(self, name):
self.name = name # instance variable
4. @classmethod and @staticmethod
----------------------------------
class Game:
@staticmethod
def rules():
print("General rules apply.")
@classmethod
def get_category(cls):
print(f"This is a {cls.__name__} class")
5. Encapsulation (Private Attributes)
--------------------------------------
class Player:
def __init__(self, name):
self.__name = name # private variable
def get_name(self):
return self.__name
6. Inheritance
----------------
class Person:
def __init__(self, name):
self.name = name
class Player(Person):
def __init__(self, name, sport):
super().__init__(name)
self.sport = sport
7. Polymorphism
-----------------
class Cricket:
def play(self):
print("Playing cricket")
class Football:
def play(self):
print("Playing football")
for game in [Cricket(), Football()]:
game.play()
8. Magic Methods
------------------
class Player:
def __init__(self, name):
self.name = name
def __str__(self):
return f"Player: {self.name}"
def __len__(self):
return len(self.name)
Common Dunder Methods:
- __init__: Constructor
- __str__: String representation
- __len__: len(obj)
- __eq__: Equality comparison
Common Interview Questions:
----------------------------
- What is `self` in Python?
- What is `__init__`?
- Difference between class and instance variable?
- What is encapsulation?
- What is polymorphism?