-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathoop_with_python.py
270 lines (205 loc) · 9.43 KB
/
oop_with_python.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
# -*- coding: utf-8 -*-
"""oop_with_Python.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/110PVRvHWszvbStmuW71BSXRZzg4-zC6j
# **Implementation of Classes and Objects**
**Definition:**
Classes and objects are the fundamental building blocks of object-oriented programming (OOP) in Python. A class defines a blueprint for objects, and objects are instances of classes.
**Importance:**
Promotes code reusability.
Encapsulates data and functions together.
Examples:
**Defining a Class and Creating an Object:**
"""
# Defining a class and creating an object
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f'{self.name} is barking.'
dog1 = Dog('Buddy', 3)
print(dog1.bark()) # Output: Buddy is barking.
"""**Explanation:**
* class Dog:: Defines a class named Dog.
* def init(self, name, age):: Defines the constructor method for the class, which initializes the object's attributes.
* def bark(self):: Defines a method named bark that returns a string.
* dog1 = Dog('Buddy', 3):: Creates an instance of the Dog class named dog1 with attributes name='Buddy' and age=3.
* print(dog1.bark()): Calls the bark method on the dog1 object and prints the result.
# **OOP Principles in Python**
**Definition:**
Object-oriented programming (OOP) in Python is based on four main principles: *Encapsulation, Inheritance, Polymorphism, and Abstraction.*
**Importance:**
* Encapsulation: Bundles data with methods that operate on the data.
*Inheritance: Enables new classes to inherit attributes and methods from existing classes.
* Polymorphism: Allows methods to be used interchangeably between different classes.
* Abstraction: Hides complex implementation details and shows only the necessary features.
**Examples:**
**Encapsulation:**
"""
# Example of encapsulation
class Car:
def __init__(self, make, model):
self.__make = make
self.__model = model
def get_car_info(self):
return f'Car: {self.__make} {self.__model}'
car = Car('Toyota', 'Corolla')
print(car.get_car_info()) # Output: Car: Toyota Corolla
"""
**Explanation:**
* class Car:: Defines a class named Car.
* def **init**(self, make, model):: Defines the constructor method for the class, which initializes the object's attributes.
* self.**make and self**.model: Private attributes.
* def get_car_info(self):: Defines a method named get_car_info that returns the car's information.
* car = Car('Toyota', 'Corolla'):: Creates an instance of the Car class named car with attributes make='Toyota' and model='Corolla'.
* print(car.get_car_info()): Calls the get_car_info method on the car object and prints the result.
**Inheritance:**"""
# Example of inheritance
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f'{self.name} says Woof!'
dog = Dog('Buddy')
print(dog.speak()) # Output: Buddy says Woof!
"""**Explanation:**
- class Animal:: Defines a base class named Animal.
- class Dog(Animal):: Defines a derived class named Dog that inherits from the Animal class.
- def speak(self):: Overrides the speak method from the base class.
- dog = Dog('Buddy'):: Creates an instance of the Dog class named dog with the attribute name='Buddy'.
- print(dog.speak()): Calls the speak method on the dog object and prints the result.
**Polymorphism:**
"""
# Example of polymorphism
class Cat(Animal):
def speak(self):
return f'{self.name} says Meow!'
animals = [Dog('Buddy'), Cat('Whiskers')]
for animal in animals:
print(animal.speak())
# Output:
# Buddy says Woof!
# Whiskers says Meow!
"""**Explanation:**
- class Cat(Animal):: Defines a derived class named Cat that inherits from the Animal class.
- def speak(self):: Overrides the speak method from the base class.
- animals = [Dog('Buddy'), Cat('Whiskers')]: Creates a list of Animal objects.
- for animal in animals:: Iterates over the list of animals and calls the speak method on each object, demonstrating polymorphism.
**Abstraction:**
"""
# Example of abstraction
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
rect = Rectangle(3, 4)
print(rect.area()) # Output: 12
"""**Explanation:**
- from abc import ABC, abstractmethod:: Imports the ABC (Abstract Base Class) and abstractmethod from the abc module.
- class Shape(ABC):: Defines an abstract base class named Shape.
- @abstractmethod def area(self):: Declares an abstract method named area that must be implemented by derived classes.
- class Rectangle(Shape):: Defines a derived class named Rectangle that inherits from the Shape class.
- def __init__(self, width, height):: Defines the constructor method for the Rectangle class.
- def area(self):: Implements the area method for the Rectangle class.
- rect = Rectangle(3, 4):: Creates an instance of the Rectangle class named rect with attributes width=3 and height=4.
- print(rect.area()): Calls the area method on the rect object and prints the result.
# Class Variables and Functions
### Definition:
Class variables are variables that are shared among all instances of a class. Class functions (or methods) are functions defined within a class and operate on instances of that class.
### Importance:
- Class variables provide a way to store data that is shared across all instances of a class.
- Class methods enable the encapsulation of behavior related to class instances.
### Examples:
**Class Variables:**
"""
# Example of class variables
class Employee:
raise_amount = 1.05 # Class variable
def __init__(self, name, salary):
self.name = name
self.salary = salary
def apply_raise(self):
self.salary = int(self.salary * Employee.raise_amount)
emp1 = Employee('Alice', 50000)
emp1.apply_raise()
print(emp1.salary) # Output: 52500
"""**Explanation:**
- class Employee:: Defines a class named Employee.
- raise_amount = 1.05: Class variable that is shared among all instances of the class.
- def __init__(self, name, salary):: Defines the constructor method for the class.
- def apply_raise(self):: Defines a method that applies a raise to the employee's salary using the class variable.
- emp1 = Employee('Alice', 50000):: Creates an instance of the Employee class named emp1 with attributes name='Alice' and salary=50000.
- emp1.apply_raise(): Calls the apply_raise method on the emp1 object.
- print(emp1.salary): Prints the salary of the emp1 object after applying the raise.
**Class Methods:**
"""
# Example of class methods
class Circle:
pi = 3.14159 # Class variable
def __init__(self, radius):
self.radius = radius
def area(self):
return Circle.pi * self.radius ** 2
circle1 = Circle(5)
print(circle1.area()) # Output: 78.53975
"""**Explanation:**
- class Circle:: Defines a class named Circle.
- pi = 3.14159: Class variable that is shared among all instances of the class.
- def __init__(self, radius):: Defines the constructor method for the class.
- def area(self):: Defines a method that calculates the area of the circle using the class variable pi.
- circle1 = Circle(5):: Creates an instance of the Circle class named circle1 with attribute radius=5.
- print(circle1.area()): Calls the area method on the circle1 object and prints the result.
## Constructors and Destructors
### Definition:
Constructors are special methods that are automatically called when an object is created. Destructors are special methods that are automatically called when an object is deleted.
### Importance:
- Constructors initialize the object's attributes.
- Destructors perform cleanup operations before an object is destroyed.
### Examples:
**Constructors:**
"""
# Example of constructor
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def display(self):
print(f'Name: {self.name}, Age: {self.age}')
person1 = Person('John', 30)
person1.display() # Output: Name: John, Age: 30
"""**Explanation:**
- class Person:: Defines a class named Person.
- def __init__(self, name, age):: Defines the constructor method for the class, which initializes the object's attributes.
- def display(self):: Defines a method that displays the person's information.
- person1 = Person('John', 30):: Creates an instance of the Person class named person1 with attributes name='John' and age=30.
- person1.display(): Calls the display method on the person1 object and prints the result.
**Destructors:**
"""
# Example of destructor
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __del__(self):
print(f'{self.name} has been deleted.')
person1 = Person('John', 30)
del person1 # Output: John has been deleted.
"""**Explanation:**
- class Person:: Defines a class named Person.
- def __init__(self, name, age):: Defines the constructor method for the class, which initializes the object's attributes.
- def __del__(self):: Defines the destructor method for the class, which performs cleanup operations before the object is destroyed.
- person1 = Person('John', 30):: Creates an instance of the Person class named person1 with attributes name='John' and age=30.
- del person1: Deletes the person1 object, which calls the destructor method and prints the result.
"""