... | @@ -100,7 +100,7 @@ T.B.W |
... | @@ -100,7 +100,7 @@ T.B.W |
|
|
|
|
|
# Procedural, Object-Oriented & Functional Programming
|
|
# Procedural, Object-Oriented & Functional Programming
|
|
|
|
|
|
There are generally three styles of code found in Python:
|
|
There are generally three styles of code found in Python.
|
|
|
|
|
|
**Procedural**
|
|
**Procedural**
|
|
|
|
|
... | @@ -134,6 +134,9 @@ class Point: |
... | @@ -134,6 +134,9 @@ class Point: |
|
|
|
|
|
def __str__(self):
|
|
def __str__(self):
|
|
pass
|
|
pass
|
|
|
|
|
|
|
|
def magnitude(self)
|
|
|
|
return sqrt(self.x ** 2 + self.y ** 2)
|
|
```
|
|
```
|
|
|
|
|
|
**Functional**
|
|
**Functional**
|
... | @@ -162,15 +165,39 @@ largest_distance = max(distances) |
... | @@ -162,15 +165,39 @@ largest_distance = max(distances) |
|
average_distance = sum(distances) / len(points)
|
|
average_distance = sum(distances) / len(points)
|
|
```
|
|
```
|
|
|
|
|
|
None of these examples are particuarly well written...
|
|
None of these examples are particularly well written...
|
|
|
|
|
|
1. No `__main__`
|
|
1. No `__main__`
|
|
2. No documentation
|
|
2. No documentation
|
|
3. Everything is in `"main"`
|
|
3. Everything is in `"main"`
|
|
|
|
|
|
# Pythonic Code
|
|
|
|
|
|
|
|
TBW
|
|
# Pythonic Code & "Good" Code
|
|
|
|
|
|
|
|
There are quite a few *"rules"* when writing Pythonic code... starting with...
|
|
|
|
|
|
|
|
- Style - [PEP 8](https://www.python.org/dev/peps/pep-0008/)
|
|
|
|
- Zen of Python - [PEP 20](https://www.python.org/dev/peps/pep-0020/)
|
|
|
|
|
|
|
|
Other rules come from the community...
|
|
|
|
|
|
|
|
1. Always have a `if __name__ == "__main__"`.
|
|
|
|
2. Use f-strings over format where possible.
|
|
|
|
3. Use `with` closures`
|
|
|
|
4. Write pydoc style documentation.
|
|
|
|
5. Use functions and modules.
|
|
|
|
6. No global variables.
|
|
|
|
7. Do not always use object-oriented design.
|
|
|
|
8. Do not forget about the [Python GIL](https://wiki.python.org/moin/GlobalInterpreterLock)
|
|
|
|
|
|
|
|
Other rules come from general software engineering practices:
|
|
|
|
|
|
|
|
1. Follow Test Driven Development (TDD)
|
|
|
|
2. Use top down design
|
|
|
|
3. Do not write monolithic functions
|
|
|
|
4. Use a code linter or style checker (e.g., pylint)
|
|
|
|
5. Use self-dcoumenting names
|
|
|
|
|
|
|
|
|
|
# Loops, Context Managers, and List/Generator Comprehensions
|
|
# Loops, Context Managers, and List/Generator Comprehensions
|
|
|
|
|
... | | ... | |