1
- #author: seema kumari patel
2
- #OOPs concept - Python
3
-
4
1
---
5
2
id : python-OOPs
6
3
title : Python OOPs concept
7
4
sidebar_label : Python OOPs concept # displays in sidebar
8
5
sidebar_position : 19
6
+ author : Seema Kumari Patel
7
+ description : OOPs concept in Python
9
8
tags :
10
9
[
11
10
Python,
12
11
Introduction of python,
13
12
Python Syntax,
14
13
Python Variables,
15
- Python Operators,
16
-
14
+ Python Operators,
17
15
]
18
-
19
16
---
20
17
21
18
@@ -31,26 +28,31 @@ Python supports the core principles of object-oriented programming, which are th
31
28
32
29
📌 ** Use Case** : create a class - car
33
30
31
+ ``` python
34
32
class Car :
35
33
def __init__ (self , brand , model ):
36
34
self .brand = brand
37
35
self .model = model
38
36
39
37
def start (self ):
40
38
print (f " { self .brand} { self .model} is starting... " )
39
+ ```
41
40
42
41
2 . Object - An instance of a class.
43
42
44
43
📌 ** Use Case** : instantiate the variables
45
44
45
+ ``` python
46
46
my_car = Car(" Tesla" , " Model S" )
47
47
my_car.start() # Tesla Model S is starting...
48
+ ```
48
49
49
50
50
51
3 . Encapsulation - Hiding the internal details and only exposing necessary parts.
51
52
52
53
📌 ** Use Case** : Not letting data to be accessed by other class
53
54
55
+ ``` python
54
56
class BankAccount :
55
57
def __init__ (self , balance ):
56
58
self .__balance = balance # private variable
@@ -60,12 +62,14 @@ class BankAccount:
60
62
61
63
def get_balance (self ):
62
64
return self .__balance
65
+ ```
63
66
64
67
65
68
4 . Inheritance - One class can inherit from another.
66
69
67
70
📌 ** Use Case** : car (parent) class is getting inherited by (child) ElectricCar
68
71
72
+ ``` python
69
73
class ElectricCar (Car ):
70
74
def __init__ (self , brand , model , battery ):
71
75
super ().__init__ (brand, model)
@@ -77,12 +81,14 @@ class ElectricCar(Car):
77
81
tesla = ElectricCar(" Tesla" , " Model X" , 100 )
78
82
tesla.start()
79
83
tesla.battery_info()
84
+ ```
80
85
81
86
82
87
5 . Polymorphism - Same function name, but different behavior depending on the object.
83
88
84
89
📌 ** Use Case** : Different classes using single method for different purposes.
85
90
91
+ ``` python
86
92
class Dog :
87
93
def speak (self ):
88
94
return " Woof!"
@@ -94,12 +100,14 @@ class Cat:
94
100
pets = [Dog(), Cat()]
95
101
for pet in pets:
96
102
print (pet.speak()) # Woof! / Meow!
103
+ ```
97
104
98
105
99
106
6 . Abstraction - Hiding implementation details, showing only essential features (using abc module).
100
107
101
108
📌 ** Use Case** : Hiding low level details
102
109
110
+ ``` python
103
111
from abc import ABC , abstractmethod
104
112
105
113
class Shape (ABC ):
@@ -116,5 +124,6 @@ class Circle(Shape):
116
124
117
125
c = Circle(5 )
118
126
print (c.area()) # 78.5
127
+ ```
119
128
120
129
0 commit comments