0% found this document useful (0 votes)
1 views29 pages

Python OOP Notes

This document provides a comprehensive overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It includes detailed explanations, examples, and code snippets for each topic, making it a valuable resource for understanding OOP principles and their application in Python. The document also features a table of contents for easy navigation through the various topics discussed.

Uploaded by

hellokaran7466
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views29 pages

Python OOP Notes

This document provides a comprehensive overview of Object-Oriented Programming (OOP) in Python, covering key concepts such as classes, objects, inheritance, polymorphism, encapsulation, and abstraction. It includes detailed explanations, examples, and code snippets for each topic, making it a valuable resource for understanding OOP principles and their application in Python. The document also features a table of contents for easy navigation through the various topics discussed.

Uploaded by

hellokaran7466
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

🐍 Python OOP Page

🐍 Python
Object-Oriented Programming

Topics Covered: Classes • Objects • Inheritance • Polymorphism • Encapsulation • Abstraction


🐍 Python OOP Page

📋 Table of Contents
No. Topic Name Subtopics

Topic 1 Introduction to OOP Concepts, Benefits, Real-world


Analogy

Topic 2 Classes and Objects Definition, Syntax, Instance vs


Class

Topic 3 Constructors __init__, Default, Parameterized

Topic 4 Attributes & Methods Instance, Class, Static attributes


and methods

Topic 5 Encapsulation Private, Protected, Public,


Getters/Setters

Topic 6 Inheritance Single, Multiple, Multilevel,


Hierarchical, Hybrid

Topic 7 Polymorphism Method Overriding, Overloading,


Duck Typing

Topic 8 Abstraction Abstract Classes, Abstract


Methods

Topic 9 Magic/Dunder Methods __str__, __repr__, __len__,


__add__ and more

Topic 10 Class & Static Methods @classmethod, @staticmethod


decorators

Topic 11 Properties @property, getter, setter, deleter

Topic 12 Composition & Aggregation Has-A relationship vs Inheritance

Topic 13 Exception Handling in OOP Custom Exceptions, try/except in


classes

Topic 14 Quick Reference Summary Cheat sheet of all OOP concepts


🐍 Python OOP Page

Topic 1: Introduction to OOP

Topic 1: Introduction to Object-Oriented Programming


Object-Oriented Programming (OOP) is a programming paradigm that organizes code
DEFINITION around 'objects' — bundles of data (attributes) and behavior (methods) — rather than just
functions and procedures.

1.1 The Four Pillars of OOP


Pillar Meaning Real-World Example

Encapsulation Bundling data and methods ATM machine hides internal logic
together; hiding internal details

Abstraction Showing only essential features, Car steering wheel — you steer,
hiding complexity not know mechanics

Inheritance Child class inherits properties A Dog inherits from Animal


from parent class

Polymorphism Same interface, different speak() works differently for Dog


behavior depending on object and Cat

1.2 Why Use OOP?


✓ Code Reusability — Write once, use many times via inheritance

✓ Modularity — Each object is independent and manageable

✓ Easy Maintenance — Changes in one class don't affect others

✓ Data Security — Encapsulation protects data from unauthorized access

✓ Real-world Modeling — Maps closely to real-world entities


🐍 Python OOP Page

Topic 2: Classes and Objects

Topic 2: Classes and Objects


A class is a blueprint or template that defines attributes (data) and methods (behavior) for
CLASS
objects.

An object is an instance of a class — a real entity created from the blueprint with actual
OBJECT
data.

2.1 Defining a Class and Creating Objects


● ● ● [Link]
1 # Defining a Class
2 class Car:
3 brand = "Generic" # Class attribute (shared by all)
4
5 def __init__(self, model, color, speed):
6 [Link] = model # Instance attribute
7 [Link] = color
8 [Link] = speed
9
10 def display_info(self):
11 print(f"Model: {[Link]}, Color: {[Link]}, Speed: {[Link]} km/h")
12
13 def accelerate(self, amount):
14 [Link] += amount
15 print(f"{[Link]} accelerated to {[Link]} km/h")
16
17 # Creating Objects (Instances)
18 car1 = Car("Tesla Model 3", "Red", 0)
19 car2 = Car("BMW X5", "Blue", 0)
20
21 # Accessing attributes
22 print([Link]) # Tesla Model 3
23 print([Link]) # Blue
24
25 # Calling methods
26 car1.display_info()
27 [Link](60)
28 car2.display_info()
🐍 Python OOP Page

▶ Output
Tesla Model 3
Blue
Model: Tesla Model 3, Color: Red, Speed: 0 km/h
Tesla Model 3 accelerated to 60 km/h
Model: BMW X5, Color: Blue, Speed: 0 km/h

2.2 Class vs Instance Attributes


Type Scope Example Where Defined

Class Attribute Shared across ALL [Link] = 'Generic' Defined inside class,
objects outside __init__

Instance Attribute Unique to EACH object [Link] = 'Tesla' Defined inside __init__
using self
🐍 Python OOP Page

Topic 3: Constructors

Topic 3: Constructors
A constructor is a special method __init__() that is automatically called when an object
CONSTRUCTOR
is created. It initializes the object's attributes.

3.1 Default Constructor


● ● ● [Link]
1 class Student:
2 def __init__(self): # Default constructor — no parameters
3 [Link] = "Unknown"
4 [Link] = 0
5 print("Student object created!")
6
7 s1 = Student()
8 print([Link]) # Unknown
9 print([Link]) # 0

▶ Output
Student object created!
Unknown
0

3.2 Parameterized Constructor


● ● ● [Link]
1 class Student:
2 def __init__(self, name, roll_no, marks):
3 [Link] = name
4 self.roll_no = roll_no
5 [Link] = marks
6
7 def show(self):
8 print(f"Name: {[Link]} | Roll No: {self.roll_no} | Marks: {[Link]}")
9
10 def grade(self):
11 if [Link] >= 90: return 'A'
12 elif [Link] >= 75: return 'B'
🐍 Python OOP Page

13 elif [Link] >= 60: return 'C'


14 else: return 'F'
15
16 stu1 = Student("Riya Sharma", 101, 92)
17 stu2 = Student("Arjun Mehta", 102, 78)
18 stu3 = Student("Priya Singh", 103, 55)
19
20 for s in [stu1, stu2, stu3]:
21 print(f"{[Link]}: Grade = {[Link]()}")
22 [Link]()

▶ Output
Riya Sharma: Grade = A
Name: Riya Sharma | Roll No: 101 | Marks: 92
Arjun Mehta: Grade = B
Name: Arjun Mehta | Roll No: 102 | Marks: 78
Priya Singh: Grade = F
Name: Priya Singh | Roll No: 103 | Marks: 55
🐍 Python OOP Page

Topic 4: Attributes and Methods

Topic 4: Attributes and Methods

4.1 Types of Methods


Method Type Parameter Use Case Syntax

Instance Method self parameter Accesses/modifies def display(self)


instance attributes

Class Method @classmethod + cls Accesses/modifies class def count(cls)


attributes

Static Method @staticmethod No self or cls; utility def validate(x)


function

● ● ● [Link]
1 class BankAccount:
2 bank_name = "National Bank" # Class attribute
3 total_accounts = 0 # Tracks all accounts
4
5 def __init__(self, owner, balance=0):
6 [Link] = owner # Instance attribute
7 [Link] = balance
8 BankAccount.total_accounts += 1
9
10 # Instance Method
11 def deposit(self, amount):
12 [Link] += amount
13 print(f"Deposited ₹{amount}. New balance: ₹{[Link]}")
14
15 def withdraw(self, amount):
16 if amount > [Link]:
17 print("Insufficient funds!")
18 else:
19 [Link] -= amount
20 print(f"Withdrawn ₹{amount}. Remaining: ₹{[Link]}")
21
22 # Class Method
23 @classmethod
24 def get_bank_info(cls):
25 print(f"Bank: {cls.bank_name} | Accounts: {cls.total_accounts}")
26
27 # Static Method
28 @staticmethod
🐍 Python OOP Page

29 def is_valid_amount(amount):
30 return amount > 0
31
32 acc1 = BankAccount("Ravi Kumar", 5000)
33 acc2 = BankAccount("Sunita Devi", 12000)
34
35 [Link](2000)
36 [Link](8000)
37 [Link](1000)
38 BankAccount.get_bank_info()
39 print("Valid amount?", BankAccount.is_valid_amount(500))

▶ Output
Deposited ₹2000. New balance: ₹7000
Insufficient funds!
Withdrawn ₹1000. Remaining: ₹6000
Bank: National Bank | Accounts: 2
Valid amount? True
🐍 Python OOP Page

Topic 5: Encapsulation

Topic 5: Encapsulation
Encapsulation is the wrapping of data (attributes) and methods into a single unit (class),
DEFINITION
and restricting direct access to internal data using access modifiers.

5.1 Access Modifiers in Python


Type Syntax Access Level Example

Public name No restriction; [Link] = 'Ravi'


accessible everywhere

Protected _name Convention: accessible self._salary = 50000


within class & subclass

Private __name Name mangling; not self.__password =


directly accessible 'abc123'
outside class

● ● ● [Link]
1 class Employee:
2 def __init__(self, name, salary, emp_id):
3 [Link] = name # Public
4 self._dept = 'General' # Protected
5 self.__salary = salary # Private
6 self.__emp_id = emp_id # Private
7
8 # Getter method
9 def get_salary(self):
10 return self.__salary
11
12 # Setter method with validation
13 def set_salary(self, new_salary):
14 if new_salary > 0:
15 self.__salary = new_salary
16 print(f"Salary updated to ₹{new_salary}")
17 else:
18 print("Invalid salary!")
19
20 def display(self):
21 print(f"Name: {[Link]} | Dept: {self._dept} | Salary: ₹{self.__salary}")
22
🐍 Python OOP Page

23 emp = Employee("Kavita Nair", 75000, "E001")


24
25 [Link]() # Works
26 print([Link]) # Works — public
27 # print(emp.__salary) # ERROR — private
28 print(emp.get_salary()) # Works via getter
29 emp.set_salary(85000) # Valid update
30 emp.set_salary(-5000) # Invalid — rejected
31 emp.set_salary(0)

▶ Output
Name: Kavita Nair | Dept: General | Salary: ₹75000
Kavita Nair
75000
Salary updated to ₹85000
Invalid salary!
Invalid salary!
🐍 Python OOP Page

Topic 6: Inheritance

Topic 6: Inheritance
Inheritance allows a child class (subclass) to inherit attributes and methods from a parent
DEFINITION
class (superclass), enabling code reuse and extending functionality.

6.1 Single Inheritance


● ● ● [Link]
1 class Animal: # Parent class
2 def __init__(self, name, age):
3 [Link] = name
4 [Link] = age
5
6 def eat(self):
7 print(f"{[Link]} is eating.")
8
9 def breathe(self):
10 print(f"{[Link]} is breathing.")
11
12 class Dog(Animal): # Child class inherits Animal
13 def __init__(self, name, age, breed):
14 super().__init__(name, age) # Call parent constructor
15 [Link] = breed
16
17 def bark(self):
18 print(f"{[Link]} says: Woof! Woof!")
19
20 def display(self):
21 print(f"Dog: {[Link]}, Age: {[Link]}, Breed: {[Link]}")
22
23 dog1 = Dog("Bruno", 3, "Labrador")
24 [Link]() # Inherited from Animal
25 [Link]() # Inherited from Animal
26 [Link]() # Own method
27 [Link]()

▶ Output
Bruno is eating.
Bruno is breathing.
Bruno says: Woof! Woof!
🐍 Python OOP Page

Dog: Bruno, Age: 3, Breed: Labrador

6.2 Multiple Inheritance


● ● ● [Link]
1 class Father:
2 def hard_working(self):
3 print("Father: I am hardworking.")
4
5 class Mother:
6 def caring(self):
7 print("Mother: I am caring.")
8
9 class Child(Father, Mother): # Inherits from both
10 def study(self):
11 print("Child: I study hard.")
12
13 c = Child()
14 c.hard_working() # From Father
15 [Link]() # From Mother
16 [Link]() # Own method
17 print(Child.__mro__)

▶ Output
Father: I am hardworking.
Mother: I am caring.
Child: I study hard.
(<class '__main__.Child'>, <class '__main__.Father'>, <class '__main__.Mother'>, <class 'object'>)

6.3 Multilevel Inheritance


● ● ● [Link]
1 class Vehicle:
2 def move(self):
3 print("Vehicle: Can move.")
4
5 class Car(Vehicle):
6 def drive(self):
7 print("Car: Can be driven.")
8
9 class ElectricCar(Car): # 3 levels deep
10 def charge(self):
11 print("ElectricCar: Can be charged.")
12
13 tesla = ElectricCar()
🐍 Python OOP Page

14 [Link]() # From Vehicle


15 [Link]() # From Car
16 [Link]() # Own method

▶ Output
Vehicle: Can move.
Car: Can be driven.
ElectricCar: Can be charged.

6.4 Types of Inheritance — Summary


Type Description Example

Single One parent, one child Dog(Animal)

Multiple Multiple parents, one child Child(Father, Mother)

Multilevel Grandparent → Parent → Child ElectricCar(Car(Vehicle))

Hierarchical One parent, multiple children Cat(Animal), Dog(Animal)

Hybrid Combination of above types Mix of multiple & multilevel


🐍 Python OOP Page

Topic 7: Polymorphism

Topic 7: Polymorphism
Polymorphism means 'many forms'. In OOP, it allows methods to behave differently based
DEFINITION
on the object calling them — same method name, different behavior.

7.1 Method Overriding (Runtime Polymorphism)


● ● ● [Link]
1 class Shape:
2 def area(self):
3 print("Shape: Area not defined.")
4
5 def describe(self):
6 print(f"I am a {self.__class__.__name__}")
7
8 class Circle(Shape):
9 def __init__(self, radius):
10 [Link] = radius
11
12 def area(self): # Overrides parent method
13 result = 3.14 * [Link] ** 2
14 print(f"Circle Area: {result:.2f}")
15
16 class Rectangle(Shape):
17 def __init__(self, length, width):
18 [Link] = length
19 [Link] = width
20
21 def area(self): # Overrides parent method
22 result = [Link] * [Link]
23 print(f"Rectangle Area: {result}")
24
25 class Triangle(Shape):
26 def __init__(self, base, height):
27 [Link] = base
28 [Link] = height
29
30 def area(self):
31 result = 0.5 * [Link] * [Link]
32 print(f"Triangle Area: {result}")
33
34 shapes = [Circle(7), Rectangle(4, 6), Triangle(5, 8)]
🐍 Python OOP Page

35
36 for shape in shapes: # Same interface, different behavior
37 [Link]()
38 [Link]()

▶ Output
I am a Circle
Circle Area: 153.86
I am a Rectangle
Rectangle Area: 24
I am a Triangle
Triangle Area: 20.0

7.2 Duck Typing


DUCK If it walks like a duck and quacks like a duck, it IS a duck. Python doesn't check the class —
TYPING it checks if the method exists.

● ● ● [Link]
1 class Dog:
2 def speak(self):
3 print("Dog says: Woof!")
4
5 class Cat:
6 def speak(self):
7 print("Cat says: Meow!")
8
9 class Duck:
10 def speak(self):
11 print("Duck says: Quack!")
12
13 class Robot:
14 def speak(self):
15 print("Robot says: Beep Boop!")
16
17 def make_sound(animal): # Doesn't care about class type
18 [Link]() # Only needs speak() to exist
19
20 animals = [Dog(), Cat(), Duck(), Robot()]
21 for a in animals:
22 make_sound(a)

▶ Output
Dog says: Woof!
🐍 Python OOP Page

Cat says: Meow!


Duck says: Quack!
Robot says: Beep Boop!
🐍 Python OOP Page

Topic 8: Abstraction

Topic 8: Abstraction
Abstraction means hiding complex implementation details and showing only the
DEFINITION necessary features. In Python, abstraction is achieved using the ABC (Abstract Base Class)
module.

● ● ● [Link]
1 from abc import ABC, abstractmethod
2
3 class PaymentGateway(ABC): # Abstract class
4
5 @abstractmethod
6 def process_payment(self, amount):
7 pass # No implementation
8
9 @abstractmethod
10 def refund(self, amount):
11 pass
12
13 def show_fee(self): # Concrete method — has implementation
14 print("Transaction fee: 2%")
15
16 class GPay(PaymentGateway): # Concrete class
17 def process_payment(self, amount):
18 print(f"GPay: Processing ₹{amount} via UPI...")
19
20 def refund(self, amount):
21 print(f"GPay: Refunding ₹{amount}...")
22
23 class CreditCard(PaymentGateway):
24 def process_payment(self, amount):
25 print(f"Credit Card: Charging ₹{amount}...")
26
27 def refund(self, amount):
28 print(f"Credit Card: Refunding ₹{amount} to your card.")
29
30 # payment = PaymentGateway() # ERROR — can't instantiate abstract class
31 g = GPay()
32 g.process_payment(500)
33 [Link](100)
34 g.show_fee()
35
🐍 Python OOP Page

36 cc = CreditCard()
37 cc.process_payment(1200)
38 [Link](200)

▶ Output
GPay: Processing ₹500 via UPI...
GPay: Refunding ₹100...
Transaction fee: 2%
Credit Card: Charging ₹1200...
Credit Card: Refunding ₹200 to your card.
🐍 Python OOP Page

Topic 9: Magic / Dunder Methods

Topic 9: Magic / Dunder Methods


Magic methods (dunder methods) are special methods with double underscores (__) on
DEFINITION
both sides. Python calls them automatically in specific situations.

9.1 Common Magic Methods


Method Purpose Triggered By

__init__ Constructor — called on object obj = MyClass()


creation

__str__ Human-readable string print(obj)


representation

__repr__ Developer-friendly representation repr(obj)

__len__ Returns length of object len(obj)

__add__ Defines + operator behavior obj1 + obj2

__eq__ Defines == operator obj1 == obj2

__lt__ Defines < operator obj1 < obj2

__del__ Destructor — called when object del obj


deleted

● ● ● [Link]
1 class Vector:
2 def __init__(self, x, y):
3 self.x = x
4 self.y = y
5
6 def __str__(self): # For print()
7 return f"Vector({self.x}, {self.y})"
8
9 def __repr__(self): # For developers
10 return f"Vector(x={self.x}, y={self.y})"
11
12 def __add__(self, other): # For +
13 return Vector(self.x + other.x, self.y + other.y)
14
15 def __eq__(self, other): # For ==
🐍 Python OOP Page

16 return self.x == other.x and self.y == other.y


17
18 def __len__(self): # For len()
19 return int((self.x**2 + self.y**2)**0.5)
20
21 v1 = Vector(3, 4)
22 v2 = Vector(1, 2)
23 v3 = Vector(3, 4)
24
25 print(v1) # Uses __str__
26 print(repr(v1)) # Uses __repr__
27 print(v1 + v2) # Uses __add__
28 print(v1 == v3) # Uses __eq__
29 print(v1 == v2) # Uses __eq__
30 print(len(v1)) # Uses __len__ (magnitude)

▶ Output
Vector(3, 4)
Vector(x=3, y=4)
Vector(4, 6)
True
False
5
🐍 Python OOP Page

Topic 10: Properties (@property)

Topic 10: Properties — @property Decorator


The @property decorator allows you to define methods that can be accessed like
DEFINITION attributes. This provides controlled access to private data without explicit getter/setter
calls.

● ● ● [Link]
1 class Temperature:
2 def __init__(self, celsius=0):
3 self._celsius = celsius # Protected attribute
4
5 @property
6 def celsius(self): # Getter
7 return self._celsius
8
9 @[Link]
10 def celsius(self, value): # Setter with validation
11 if value < -273.15:
12 raise ValueError("Temperature below absolute zero!")
13 self._celsius = value
14
15 @property
16 def fahrenheit(self): # Computed property
17 return (self._celsius * 9/5) + 32
18
19 @property
20 def kelvin(self): # Another computed property
21 return self._celsius + 273.15
22
23 temp = Temperature(100)
24 print(f'Celsius: {[Link]}') # Like attribute, not method
25 print(f'Fahrenheit: {[Link]}')
26 print(f'Kelvin: {[Link]}')
27
28 [Link] = 0 # Uses setter
29 print(f'Freezing point: {[Link]}F')
30
31 try:
32 [Link] = -300 # Triggers validation
33 except ValueError as e:
34 print(f"Error: {e}")
🐍 Python OOP Page

▶ Output
Celsius: 100
Fahrenheit: 212.0
Kelvin: 373.15
Freezing point: 32.0F
Error: Temperature below absolute zero!
🐍 Python OOP Page

Topic 11: Composition & Aggregation

Topic 11: Composition and Aggregation


Type Relationship Example Code Pattern

Inheritance IS-A relationship A Dog IS-A Animal Dog(Animal)

Composition HAS-A (strong) A Car HAS-A Engine [Link] = Engine()


(engine dies with car)

Aggregation HAS-A (weak) A School HAS Students [Link] =


(students exist student_list
independently)

● ● ● [Link]
1 # Composition Example — Engine is part of Car (tightly coupled)
2 class Engine:
3 def __init__(self, hp, fuel_type):
4 [Link] = hp
5 self.fuel_type = fuel_type
6
7 def start(self):
8 print(f"Engine started — {[Link]}HP {self.fuel_type} engine roaring!")
9
10 class Wheel:
11 def __init__(self, size):
12 [Link] = size
13
14 class Car:
15 def __init__(self, brand, engine_hp, fuel, wheel_size):
16 [Link] = brand
17 [Link] = Engine(engine_hp, fuel) # Composition
18 [Link] = [Wheel(wheel_size) for _ in range(4)]
19
20 def start_car(self):
21 print(f"{[Link]}: Starting...")
22 [Link]()
23 print(f"All {len([Link])} wheels ({[Link][0].size}") ready.")
24
25 my_car = Car("Maruti Swift", 90, "Petrol", 15)
26 my_car.start_car()
27
28 # Aggregation Example — Students exist independently of Classroom
29 class Student:
30 def __init__(self, name):
🐍 Python OOP Page

31 [Link] = name
32
33 class Classroom:
34 def __init__(self, room_no):
35 self.room_no = room_no
36 [Link] = [] # Aggregation
37
38 def add_student(self, student):
39 [Link](student)
40
41 def roll_call(self):
42 print(f"Room {self.room_no} roll call:")
43 for i, s in enumerate([Link], 1):
44 print(f" {i}. {[Link]}")
45
46 room = Classroom("5-A")
47 room.add_student(Student("Aisha"))
48 room.add_student(Student("Ravi"))
49 room.add_student(Student("Meera"))
50 room.roll_call()

▶ Output
Maruti Swift: Starting...
Engine started — 90HP Petrol engine roaring!
All 4 wheels (15") ready.
Room 5-A roll call:
1. Aisha
2. Ravi
3. Meera
🐍 Python OOP Page

Topic 12: Exception Handling in OOP

Topic 12: Exception Handling in OOP


● ● ● [Link]
1 # Custom Exception Classes
2 class InsufficientFundsError(Exception):
3 def __init__(self, amount, balance):
4 [Link] = amount
5 [Link] = balance
6 super().__init__(f'Cannot withdraw ₹{amount}. Balance: ₹{balance}')
7
8 class NegativeAmountError(Exception):
9 pass
10
11 class BankAccount:
12 def __init__(self, owner, balance=0):
13 [Link] = owner
14 self.__balance = balance
15
16 def deposit(self, amount):
17 if amount <= 0:
18 raise NegativeAmountError('Deposit amount must be positive!')
19 self.__balance += amount
20 print(f"Deposited ₹{amount}. Balance: ₹{self.__balance}")
21
22 def withdraw(self, amount):
23 if amount <= 0:
24 raise NegativeAmountError('Withdrawal must be positive!')
25 if amount > self.__balance:
26 raise InsufficientFundsError(amount, self.__balance)
27 self.__balance -= amount
28 print(f"Withdrawn ₹{amount}. Balance: ₹{self.__balance}")
29
30 acc = BankAccount("Ramesh", 10000)
31
32 try:
33 [Link](5000)
34 [Link](3000)
35 [Link](20000) # This will raise exception
36 except InsufficientFundsError as e:
37 print(f"Transaction Failed: {e}")
38 except NegativeAmountError as e:
39 print(f"Invalid Input: {e}")
40 finally:
41 print("Transaction complete.")
🐍 Python OOP Page

▶ Output
Deposited ₹5000. Balance: ₹15000
Withdrawn ₹3000. Balance: ₹12000
Transaction Failed: Cannot withdraw ₹20000. Balance: ₹12000
Transaction complete.
🐍 Python OOP Page

Topic 13: Quick Reference Cheat Sheet

Topic 13: OOP Quick Reference Cheat Sheet


Syntax Purpose

class MyClass: Define a class

def __init__(self, x): Constructor with parameter

[Link] = value Set instance attribute

[Link] Access class attribute

obj = MyClass() Create an object

class Child(Parent): Inherit from Parent

super().__init__() Call parent constructor

@abstractmethod Declare abstract method

@property Create a property (getter)

@[Link] Create a setter

@classmethod Class method decorator

@staticmethod Static method decorator

def __str__(self): String representation

def __add__(self, other): Overload + operator

from abc import ABC, abstractmethod Import for abstraction

isinstance(obj, Class) Check if obj is instance of Class

issubclass(Child, Parent) Check class hierarchy

obj.__class__.__name__ Get class name of object

Access Modifiers Summary


● ● ● [Link]
1 class MyClass:
2 def __init__(self):
3 [Link] = 'accessible everywhere'
4 self._protected = 'convention: avoid from outside'
5 self.__private = 'name-mangled: _MyClass__private'
6
7 obj = MyClass()
🐍 Python OOP Page

8 print([Link]) # OK
9 print(obj._protected) # Works but not recommended
10 # print(obj.__private) # AttributeError
11 print(obj._MyClass__private) # Works (name mangling)

🎓 Python OOP
Master Classes • Objects • Inheritance • Polymorphism • Encapsulation • Abstraction

You might also like