... | ... | @@ -100,7 +100,73 @@ T.B.W |
|
|
|
|
|
# Procedural, Object-Oriented & Functional Programming
|
|
|
|
|
|
TBW
|
|
|
There are generally three styles of code found in Python:
|
|
|
|
|
|
**Procedural**
|
|
|
|
|
|
```python
|
|
|
|
|
|
point1 = (0, 5)
|
|
|
point2 = (8, 3)
|
|
|
point3 = (1, 7)
|
|
|
|
|
|
points = [point1, point2, point3]
|
|
|
|
|
|
for point in points:
|
|
|
print(sqrt(point.x ** 2 + point.y ** 2))
|
|
|
|
|
|
```
|
|
|
|
|
|
**Object Oriented**
|
|
|
|
|
|
```python
|
|
|
class Point:
|
|
|
|
|
|
def __init__(self, x, y):
|
|
|
self.x = x
|
|
|
self.y = y
|
|
|
|
|
|
def __eq__(self):
|
|
|
pass
|
|
|
|
|
|
def __hash__(self):
|
|
|
pass
|
|
|
|
|
|
def __str__(self):
|
|
|
pass
|
|
|
```
|
|
|
|
|
|
**Functional**
|
|
|
|
|
|
```python
|
|
|
point1 = (0, 5)
|
|
|
point2 = (8, 3)
|
|
|
point3 = (1, 7)
|
|
|
|
|
|
points = [point1, point2, point3]
|
|
|
|
|
|
shortest_distance = min((sqrt(point.x ** 2 + point.y ** 2)) for point in points)
|
|
|
largest_distance = max((sqrt(point.x ** 2 + point.y ** 2)) for point in points)
|
|
|
average_distance = sum((sqrt(point.x ** 2 + point.y ** 2)) for point in points) / len(points)
|
|
|
```
|
|
|
|
|
|
Of course... we should clean it up...
|
|
|
|
|
|
```python
|
|
|
points = [(0, 5), (8, 3), (1, 7)]
|
|
|
|
|
|
distances = [sqrt(point.x ** 2 + point.y ** 2) for point in points]
|
|
|
|
|
|
shortest_distance = min(distances)
|
|
|
largest_distance = max(distances)
|
|
|
average_distance = sum(distances) / len(points)
|
|
|
```
|
|
|
|
|
|
None of these examples are particuarly well written...
|
|
|
|
|
|
1. No `__main__`
|
|
|
2. No documentation
|
|
|
3. Everything is in `"main"`
|
|
|
|
|
|
# Pythonic Code
|
|
|
|
... | ... | |