├── .editorconfig
├── .github
├── FUNDING.yml
├── ISSUE_TEMPLATE
│ ├── bug_report.md
│ └── feature_request.md
├── PULL_REQUEST_TEMPLATE.md
└── workflows
│ └── ci.yml
├── .gitignore
├── .replit
├── CODE_OF_CONDUCT.md
├── CONTRIBUTING.md
├── LICENSE
├── README.de.md
├── README.es.md
├── README.hi.md
├── README.ko.md
├── README.md
├── README.zh_tw.md
├── codecov.yml
├── images
└── ultimatepython.webp
├── pyproject.toml
├── requirements.txt
├── runner.py
└── ultimatepython
├── __init__.py
├── advanced
├── __init__.py
├── async.py
├── benchmark.py
├── context_manager.py
├── data_format.py
├── date_time.py
├── decorator.py
├── file_handling.py
├── meta_class.py
├── mixin.py
├── mocking.py
├── mro.py
├── regex.py
├── thread.py
└── weak_ref.py
├── classes
├── __init__.py
├── abstract_class.py
├── basic_class.py
├── encapsulation.py
├── exception_class.py
├── inheritance.py
└── iterator_class.py
├── data_structures
├── __init__.py
├── comprehension.py
├── defaultdict.py
├── deque.py
├── dict.py
├── heap.py
├── list.py
├── namedtuple.py
├── set.py
├── string.py
└── tuple.py
└── syntax
├── __init__.py
├── bitwise.py
├── conditional.py
├── expression.py
├── function.py
├── loop.py
└── variable.py
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | end_of_line = lf
6 | insert_final_newline = true
7 | trim_trailing_whitespace = true
8 |
9 | [*.{py,toml}]
10 | indent_size = 4
11 | indent_style = space
12 |
13 | [*.{xml,yaml,yml}]
14 | indent_size = 2
15 | indent_style = space
16 |
--------------------------------------------------------------------------------
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | github: huangsam
2 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/bug_report.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Bug report
3 | about: Create a report to help us improve
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Describe the bug**
11 | A clear and concise description of what the bug is.
12 |
13 | **To Reproduce**
14 | Steps to reproduce the behavior:
15 | 1. Go to '...'
16 | 2. Click on '....'
17 | 3. Scroll down to '....'
18 | 4. See error
19 |
20 | **Expected behavior**
21 | A clear and concise description of what you expected to happen.
22 |
23 | **Screenshots**
24 | If applicable, add screenshots to help explain your problem.
25 |
26 | **Desktop (please complete the following information):**
27 | - OS: [e.g. iOS]
28 | - Browser [e.g. chrome, safari]
29 | - Version [e.g. 22]
30 |
31 | **Smartphone (please complete the following information):**
32 | - Device: [e.g. iPhone6]
33 | - OS: [e.g. iOS8.1]
34 | - Browser [e.g. stock browser, safari]
35 | - Version [e.g. 22]
36 |
37 | **Additional context**
38 | Add any other context about the problem here.
39 |
--------------------------------------------------------------------------------
/.github/ISSUE_TEMPLATE/feature_request.md:
--------------------------------------------------------------------------------
1 | ---
2 | name: Feature request
3 | about: Suggest an idea for this project
4 | title: ''
5 | labels: ''
6 | assignees: ''
7 |
8 | ---
9 |
10 | **Is your feature request related to a problem? Please describe.**
11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12 |
13 | **Describe the solution you'd like**
14 | A clear and concise description of what you want to happen.
15 |
16 | **Describe alternatives you've considered**
17 | A clear and concise description of any alternative solutions or features you've considered.
18 |
19 | **Additional context**
20 | Add any other context or screenshots about the feature request here.
21 |
--------------------------------------------------------------------------------
/.github/PULL_REQUEST_TEMPLATE.md:
--------------------------------------------------------------------------------
1 | *Please read the [contributing guidelines](https://github.com/huangsam/ultimate-python/blob/main/CONTRIBUTING.md) before submitting a pull request.*
2 |
3 | ---
4 |
5 | **Describe the change**
6 | A clear and concise description of what the change is.
7 |
8 | **Additional context**
9 | Add any other context or screenshots about the pull request here.
10 |
--------------------------------------------------------------------------------
/.github/workflows/ci.yml:
--------------------------------------------------------------------------------
1 | name: CI
2 |
3 | on:
4 | push:
5 | branches: [main]
6 | pull_request:
7 | branches: [main]
8 |
9 | permissions:
10 | contents: read
11 |
12 | jobs:
13 | python-build:
14 | name: Python 3.13
15 | runs-on: ubuntu-latest
16 |
17 | steps:
18 | - name: Checkout code
19 | uses: actions/checkout@v4
20 | - name: Set up Python 3.13
21 | uses: actions/setup-python@v5
22 | with:
23 | python-version: '3.13'
24 | - name: Install dependencies
25 | run: |
26 | python -m pip install --upgrade pip
27 | pip install -r requirements.txt
28 | - name: Lint with ruff
29 | run: |
30 | ruff check
31 | - name: Run tests and report with coverage
32 | run: |
33 | coverage run runner.py
34 | coverage report
35 | - name: Generate coverage.xml artifact
36 | run: |
37 | coverage xml -o ./coverage.xml
38 | - name: Upload coverage data to Codecov
39 | uses: codecov/codecov-action@v4
40 | with:
41 | files: ./coverage.xml
42 | token: ${{ secrets.CODECOV_TOKEN }}
43 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # System
2 | .DS_Store
3 |
4 | # IDE
5 | .idea/
6 | .vscode/
7 |
8 | # Python
9 | *.pyc
10 | .coverage
11 | coverage.json
12 | coverage.xml
13 | *.egg-info/
14 | .ruff_cache/
15 | __pycache__/
16 | build/
17 | htmlcov/
18 | venv/
19 |
--------------------------------------------------------------------------------
/.replit:
--------------------------------------------------------------------------------
1 | language = "python3"
2 | run = "python runner.py"
3 |
--------------------------------------------------------------------------------
/CODE_OF_CONDUCT.md:
--------------------------------------------------------------------------------
1 | # Contributor Covenant Code of Conduct
2 |
3 | ## Our Pledge
4 |
5 | In the interest of fostering an open and welcoming environment, we as
6 | contributors and maintainers pledge to making participation in our project and
7 | our community a harassment-free experience for everyone, regardless of age, body
8 | size, disability, ethnicity, sex characteristics, gender identity and expression,
9 | level of experience, education, socio-economic status, nationality, personal
10 | appearance, race, religion, or sexual identity and orientation.
11 |
12 | ## Our Standards
13 |
14 | Examples of behavior that contributes to creating a positive environment
15 | include:
16 |
17 | * Using welcoming and inclusive language
18 | * Being respectful of differing viewpoints and experiences
19 | * Gracefully accepting constructive criticism
20 | * Focusing on what is best for the community
21 | * Showing empathy towards other community members
22 |
23 | Examples of unacceptable behavior by participants include:
24 |
25 | * The use of sexualized language or imagery and unwelcome sexual attention or
26 | advances
27 | * Trolling, insulting/derogatory comments, and personal or political attacks
28 | * Public or private harassment
29 | * Publishing others' private information, such as a physical or electronic
30 | address, without explicit permission
31 | * Other conduct which could reasonably be considered inappropriate in a
32 | professional setting
33 |
34 | ## Our Responsibilities
35 |
36 | Project maintainers are responsible for clarifying the standards of acceptable
37 | behavior and are expected to take appropriate and fair corrective action in
38 | response to any instances of unacceptable behavior.
39 |
40 | Project maintainers have the right and responsibility to remove, edit, or
41 | reject comments, commits, code, wiki edits, issues, and other contributions
42 | that are not aligned to this Code of Conduct, or to ban temporarily or
43 | permanently any contributor for other behaviors that they deem inappropriate,
44 | threatening, offensive, or harmful.
45 |
46 | ## Scope
47 |
48 | This Code of Conduct applies both within project spaces and in public spaces
49 | when an individual is representing the project or its community. Examples of
50 | representing a project or community include using an official project e-mail
51 | address, posting via an official social media account, or acting as an appointed
52 | representative at an online or offline event. Representation of a project may be
53 | further defined and clarified by project maintainers.
54 |
55 | ## Enforcement
56 |
57 | Instances of abusive, harassing, or otherwise unacceptable behavior may be
58 | reported by contacting the project team at samhuang91@gmail.com. All
59 | complaints will be reviewed and investigated and will result in a response that
60 | is deemed necessary and appropriate to the circumstances. The project team is
61 | obligated to maintain confidentiality with regard to the reporter of an incident.
62 | Further details of specific enforcement policies may be posted separately.
63 |
64 | Project maintainers who do not follow or enforce the Code of Conduct in good
65 | faith may face temporary or permanent repercussions as determined by other
66 | members of the project's leadership.
67 |
68 | ## Attribution
69 |
70 | This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71 | available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72 |
73 | [homepage]: https://www.contributor-covenant.org
74 |
75 | For answers to common questions about this code of conduct, see
76 | https://www.contributor-covenant.org/faq
77 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # 🚀 Welcome to the Ultimate Python Study Guide! 📚
2 |
3 | 🎉 Thank you for considering contributing to this awesome project! 🎉
4 |
5 | But first, before you jump in, let's vibe with our [Code of Conduct](CODE_OF_CONDUCT.md). We want this space to be 🌈 inclusive, respectful, and nothing but fun!
6 |
7 | ## 🐍 What's This All About?
8 |
9 | Our Python Study Guide is your ticket to Python mastery! 🐍 This place is all about energy, excitement, and pure Python magic. 💫
10 |
11 | ## 📖 Let's Talk Documentation
12 |
13 | Our README is like the opening act at a concert. It's where the party starts, and we want it to be sensational! Here are the keys to this performance:
14 |
15 | - Translations? 🌍 Yes, they're right at the top for everyone to enjoy!
16 | - Python modules? 🤓 Oh, they've got a VIP seat in our Table of Contents (ToC).
17 | - External links? 🔗 They're all about HTTPS and that sweet `2xx` status.
18 | - Python documentation? For both newbies and wizards, it's all in here!
19 | - GitHub repositories? 🌟 We love stars! If it's got at least 1k stars, bring it on!
20 | - Practice resources? 🏋️♂️ We've got Python exercises to keep you in shape.
21 |
22 | ## 📚 Get into Python Modules
23 |
24 | Our Python modules are like mini-python-parties that you can host anywhere! They're packed with energy and make learning a blast! 🎉
25 |
26 | ### 🧩 The Setup
27 |
28 | Each Python module follows a rock-solid structure:
29 |
30 | ```python
31 | # The main event 🎉
32 | def main():
33 | # Here's where the magic happens!
34 | assert 1 + 1 == 2
35 | assert True is not False
36 |
37 | # The show must go on
38 | if __name__ == "__main__":
39 | main()
40 | ```
41 |
42 | If there's more Python goodness, it's up front before the main event!
43 |
44 | ### ✨ Style and Shine
45 |
46 | We've got style, oh baby! Check out the PEPs:
47 |
48 | - [PEP 8](https://www.python.org/dev/peps/pep-0008) - Our fashion bible!
49 | - [PEP 257](https://www.python.org/dev/peps/pep-0257) - Docstring Glamour!
50 |
51 | But there's more! We have our own style:
52 |
53 | - Imports are perfectly sorted with [isort](https://github.com/timothycrosley/isort).
54 | - Constants? They follow the `_UNDER_SCORE_FIRST` party rule.
55 | - Strings love double-quotes, but if there's a `"`, they'll use single quotes!
56 | - For dynamic strings, it's all about those fabulous f-strings! 🎤
57 |
58 | ### 📈 Code Coverage Stars
59 |
60 | We like to keep the energy high, and that means every module should have a whopping 80-100% code coverage! Our modules are like dance floors, and we don't want any empty spaces. That's because each module is a standalone lesson, and the `main` function is where the magic happens.
61 |
62 | ## 🌟 Your Contribution
63 |
64 | Your contributions are like the encore at a concert - they're a big deal! We appreciate your dedication to making this project even more amazing. Don't hesitate to reach out if you have any questions. Your contributions, no matter how small, are making a big difference in the Python learning world!
65 |
66 | So, get ready to rock and roll, Python style! 🤘🐍💥
67 |
68 | # 💥 Dive into the Python World
69 |
70 | Python is a versatile language used in web development, data analysis, artificial intelligence, and more. As a contributor, you're joining a vibrant community of learners and mentors.
71 |
72 | # 🧑💻 Learning Together
73 |
74 | Our project isn't just a repository; it's a collaborative learning experience. You can learn from the contributions of others and share your Python wisdom with the world. Together, we can unlock the true potential of this fantastic language.
75 |
76 | # 🚀 Opportunities Galore
77 |
78 | When you contribute to this project, you're not just improving it; you're also enhancing your own skills. You might discover new Python tricks, learn more about best practices, and even find inspiration for your own projects.
79 |
80 | # 🌍 Global Impact
81 |
82 | Python is a worldwide phenomenon, and your contributions will impact Python enthusiasts globally. Your work can help someone on the other side of the planet learn Python, kickstart their career, or solve a problem they've been struggling with.
83 |
84 | # 🙋♀️ Join a Supportive Community
85 |
86 | Our community is welcoming and supportive. If you have questions or need guidance, don't hesitate to ask. We're all here to help each other and grow together.
87 |
88 | # 📢 Your Voice Matters
89 |
90 | Your unique perspective is valuable. If you have ideas to make this guide even more engaging or fun, share them with us! We're open to creative and innovative suggestions.
91 |
92 | # 🤖 Evolving with Python
93 |
94 | Python is constantly evolving, and so is our guide. You can help keep it up-to-date, ensuring that learners always have access to the latest Python features and best practices.
95 |
96 | # 🎉 Your Contribution Matters
97 |
98 | Your contributions, whether they are big or small, are the building blocks of our project's success. Together, we're creating a resource that makes Python more accessible and exciting.
99 |
100 | # 🌟 Be a Python Star
101 |
102 | By contributing to this project, you're becoming a Python star, and you're helping others shine brightly too. Let's light up the Python world together!
103 |
104 | ## How to Contribute
105 |
106 | Ready to dive in? Here's how you can contribute:
107 |
108 | 1. **Fork the Repository**: Head to [https://github.com/huangsam/ultimate-python/](https://github.com/huangsam/ultimate-python/) and click the "Fork" button in the top right corner.
109 |
110 | 2. **Clone Your Fork**: After forking, you'll have your copy of the repository. Clone it to your local machine.
111 |
112 | 3. **Make Your Contributions**: Create or update Python modules, documentation, or anything that adds value to the project.
113 |
114 | 4. **Push Your Changes**: Once your work is ready, push your changes to your forked repository.
115 |
116 | 5. **Create a Pull Request**: Head back to the original repository (https://github.com/huangsam/ultimate-python/) and create a pull request. Describe your changes and let us know why they're awesome.
117 |
118 | We're excited to see what you bring to the table! Your contributions are making the Python world a better place.
119 |
120 | Please don't hesitate to reach out if you have any questions. Your contributions, no matter how small, are making a big difference! 🌟🐍💥
121 |
122 | ## Feel the Pythonic Energy - Contribute Now!🔥
123 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2020 Samuel Huang
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.de.md:
--------------------------------------------------------------------------------
1 | # Ultimativer Python-Lernführer
2 |
3 | [](https://github.com/huangsam/ultimate-python/actions)
4 | [](https://codecov.io/gh/huangsam/ultimate-python)
5 | [](https://sonarcloud.io/dashboard?id=huangsam_ultimate-python)
6 | [](https://github.com/huangsam/ultimate-python/blob/main/LICENSE)
7 | [](https://www.reddit.com/r/Python/comments/inllmf/ultimate_python_study_guide/)
8 |
9 | Der ultimative Python-Lernführer für Einsteiger und Profis gleichermaßen. 🐍 🐍 🐍
10 |
11 | ```python
12 | print("Ultimativer Python-Lernführer")
13 | ```
14 |
15 | [English](README.md) |
16 | [한국어](README.ko.md) |
17 | [繁体中文](README.zh_tw.md) |
18 | [Español](README.es.md) |
19 | [Deutsch](README.de.md) |
20 | [हिन्दी](README.hi.md)
21 |
22 |
23 |
24 | ## Motivation
25 |
26 | Ich habe dieses GitHub-Repository erstellt, um meine Erkenntnisse über [core Python](https://www.python.org/)
27 | in den letzten 5 Jahren als Hochschulabsolvent, Angestellter in
28 | großen Unternehmen und als Open-Source-Mitarbeiter von Repositories wie
29 | [Celery](https://github.com/celery/celery) und
30 | [Full Stack Python](https://github.com/mattmakai/fullstackpython.com) weiterzugeben.
31 | Ich freue mich darauf, dass noch mehr Menschen Python lernen und damit ihren Leidenschaften nachgehen. 🎓
32 |
33 | ## Ziele
34 |
35 | Dies sind die Hauptziele bei der Erstellung dieses Leitfadens:
36 |
37 | 🏆 **Als Ressource fungieren** für Python-Neulinge, die es vorziehen, praktisch zu lernen.
38 | Dieses Repository enthält eine Sammlung von eigenständigen Modulen, die in einer IDE
39 | wie [PyCharm](https://www.jetbrains.com/pycharm/) und im Browser wie
40 | [Replit](https://replit.com/languages/python3). Wleches wie ein einfaches Terminal
41 | mit den Beispielen funktioniert. Die meisten Zeilen haben sorgfältig ausgearbeitete Kommentare, die den Leser
42 | Schritt für Schritt durch das Programm führen. Die Benutzer werden ermutigt, den
43 | Quellcode überall zu ändern, solange die "Haupt"-Routinen nicht gelöscht werden und
44 | [run successfully](runner.py) nach jeder Änderung.
45 |
46 | 🏆 **Als reiner Leitfaden dienen** für diejenigen, die die wichtigsten Python-Konzepte wiederholen möchten.
47 | Wo nur [builtin libraries](https://docs.python.org/3/library/) genutzt werden, so dass
48 | diese Konzepte ohne den Overhead der bereichsspezifischen Konzepte vermittelt werden können. Als
49 | beliebte Open-Source-Bibliotheken und -Frameworks (d.h. `sqlalchemy`, `requests`,
50 | `pandas`) nicht installiert sind. Das Lesen des Quellcodes dieser Frameworks ist jedoch
51 | inspirierend und wird dringend empfohlen, wenn Sie ein echter Profi werden wollen.
52 | [Pythonista](https://www.urbandictionary.com/define.php?term=pythonista).
53 |
54 | ## Erste Schritte
55 |
56 | [](https://replit.com/github/huangsam/ultimate-python)
57 |
58 | Klicken Sie auf das obige Abzeichen, um eine Arbeitsumgebung im Browser zu starten, ohne
59 | ohne dass Sie Git und Python auf Ihrem lokalen Rechner installiert haben müssen. Wenn diese Voraussetzungen
60 | bereits erfüllt sind, können Sie das Repository direkt klonen.
61 |
62 | Sobald das Repository zugänglich ist, können Sie mit den eigenständigen
63 | Modulen lernen. Um den größtmöglichen Nutzen aus jedem Modul zu ziehen, lesen Sie den Modulcode und führen Sie ihn aus.
64 | Es gibt zwei Möglichkeiten, die Module auszuführen:
65 |
66 | 1. Führen Sie ein einzelnes Modul aus: `python ultimatepython/syntax/variable.py`
67 | 2. Führen Sie alle Module aus: `python runner.py`
68 |
69 | ## Inhaltsübersicht
70 |
71 | 📚 = Externe Ressource,
72 | 🍰 = Thema für Anfänger,
73 | 🤯 = Fortgeschrittenes Thema
74 |
75 | 1. **Über Python**
76 | - Overview: [What is Python](https://github.com/trekhleb/learn-python/blob/master/src/getting_started/what_is_python.md) ( 📚, 🍰 )
77 | - Design philosophy: [The Zen of Python](https://www.python.org/dev/peps/pep-0020/) ( 📚 )
78 | - Style guide: [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) ( 📚, 🤯 )
79 | - Data model: [Data model](https://docs.python.org/3/reference/datamodel.html) ( 📚, 🤯 )
80 | - Standard library: [The Python Standard Library](https://docs.python.org/3/library/) ( 📚, 🤯 )
81 | - Built-in functions: [Built-in Functions](https://docs.python.org/3/library/functions.html) ( 📚 )
82 | 2. **Syntax**
83 | - Variable: [Built-in literals](ultimatepython/syntax/variable.py) ( 🍰 )
84 | - Expression: [Numeric operations](ultimatepython/syntax/expression.py) ( 🍰 )
85 | - Bitwise: [Bitwise operators](ultimatepython/syntax/bitwise.py) ( 🍰 ), [One's/Two's Complement](https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/) ( 📚 )
86 | - Conditional: [if | if-else | if-elif-else](ultimatepython/syntax/conditional.py) ( 🍰 )
87 | - Loop: [for-loop | while-loop](ultimatepython/syntax/loop.py) ( 🍰 )
88 | - Function: [def | lambda](ultimatepython/syntax/function.py) ( 🍰 )
89 | 3. **Daten-Strukturen**
90 | - List: [List operations](ultimatepython/data_structures/list.py) ( 🍰 )
91 | - Tuple: [Tuple operations](ultimatepython/data_structures/tuple.py)
92 | - Set: [Set operations](ultimatepython/data_structures/set.py)
93 | - Dict: [Dictionary operations](ultimatepython/data_structures/dict.py) ( 🍰 )
94 | - Comprehension: [list | tuple | set | dict](ultimatepython/data_structures/comprehension.py)
95 | - String: [String operations](ultimatepython/data_structures/string.py) ( 🍰 )
96 | - Deque: [deque](ultimatepython/data_structures/deque.py) ( 🤯 )
97 | - Namedtuple: [namedtuple](ultimatepython/data_structures/namedtuple.py) ( 🤯 )
98 | - Defaultdict: [defaultdict](ultimatepython/data_structures/defaultdict.py) ( 🤯 )
99 | - Time complexity: [cPython operations](https://wiki.python.org/moin/TimeComplexity) ( 📚, 🤯 )
100 | 4. **Klassen**
101 | - Basic class: [Basic definition](ultimatepython/classes/basic_class.py) ( 🍰 )
102 | - Inheritance: [Inheritance](ultimatepython/classes/inheritance.py) ( 🍰 )
103 | - Abstract class: [Abstract definition](ultimatepython/classes/abstract_class.py)
104 | - Exception class: [Exception definition](ultimatepython/classes/exception_class.py)
105 | - Iterator class: [Iterator definition | yield](ultimatepython/classes/iterator_class.py) ( 🤯 )
106 | - Encapsulation: [Encapsulation definition](ultimatepython/classes/encapsulation.py)
107 | 5. **Fortgeschrittene**
108 | - Decorator: [Decorator definition | wraps](ultimatepython/advanced/decorator.py) ( 🤯 )
109 | - File Handling: [File Handling](ultimatepython/advanced/file_handling.py) ( 🤯 )
110 | - Context manager: [Context managers](ultimatepython/advanced/context_manager.py) ( 🤯 )
111 | - Method resolution order: [mro](ultimatepython/advanced/mro.py) ( 🤯 )
112 | - Mixin: [Mixin definition](ultimatepython/advanced/mixin.py) ( 🤯 )
113 | - Metaclass: [Metaclass definition](ultimatepython/advanced/meta_class.py) ( 🤯 )
114 | - Thread: [ThreadPoolExecutor](ultimatepython/advanced/thread.py) ( 🤯 )
115 | - Asyncio: [async | await](ultimatepython/advanced/async.py) ( 🤯 )
116 | - Weak reference: [weakref](ultimatepython/advanced/weak_ref.py) ( 🤯 )
117 | - Benchmark: [cProfile | pstats](ultimatepython/advanced/benchmark.py) ( 🤯 )
118 | - Mocking: [MagicMock | PropertyMock | patch](ultimatepython/advanced/mocking.py) ( 🤯 )
119 | - Regular expression: [search | findall | match | fullmatch](ultimatepython/advanced/regex.py) ( 🤯 )
120 | - Data format: [json | xml | csv](ultimatepython/advanced/data_format.py) ( 🤯 )
121 | - Datetime: [datetime | timezone](ultimatepython/advanced/date_time.py) ( 🤯 )
122 |
123 | ## Zusätzliche Ressourcen
124 |
125 | 👔 = Interview-Ressource,
126 | 🧪 = Code-Beispiele,
127 | 🧠 = Projektideen
128 |
129 | ### GitHub repositories
130 |
131 | Lernen Sie weiter, indem Sie von anderen Quellen lesen.
132 |
133 | - [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) ( 👔, 🧪 )
134 | - [faif/python-patterns](https://github.com/faif/python-patterns) ( 👔, 🧪 )
135 | - [geekcomputers/Python](https://github.com/geekcomputers/Python) ( 🧪 )
136 | - [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) ( 🧪 )
137 | - [karan/Projects](https://github.com/karan/Projects) ( 🧠 )
138 | - [MunGell/awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) ( 🧠 )
139 | - [vinta/awesome-python](https://github.com/vinta/awesome-python)
140 | - [academic/awesome-datascience](https://github.com/academic/awesome-datascience)
141 | - [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
142 | - [ZuzooVn/machine-learning-for-software-engineers](https://github.com/ZuzooVn/machine-learning-for-software-engineers)
143 | - [30-seconds/30-seconds-of-python](https://github.com/30-seconds/30-seconds-of-python) ( 🧪 )
144 | - [ml-tooling/best-of-python](https://github.com/ml-tooling/best-of-python)
145 | - [practical-tutorials/project-based-learning](https://github.com/practical-tutorials/project-based-learning#python)
146 | - [freeCodeCamp/freeCodeCamp](https://github.com/freeCodeCamp/freeCodeCamp) ( 👔 )
147 |
148 | ### Interaktive Übungen
149 |
150 | Üben Sie weiter, damit Ihre Programmierkenntnisse nicht einrosten.
151 |
152 | - [codechef.com](https://www.codechef.com/) ( 👔 )
153 | - [codeforces.com](https://codeforces.com/)
154 | - [codementor.io](https://www.codementor.io) ( 🧠 )
155 | - [coderbyte.com](https://www.coderbyte.com/) ( 👔 )
156 | - [codewars.com](https://www.codewars.com/)
157 | - [exercism.io](https://exercism.io/)
158 | - [geeksforgeeks.org](https://www.geeksforgeeks.org/) ( 👔 )
159 | - [hackerearth.com](https://www.hackerearth.com/)
160 | - [hackerrank.com](https://www.hackerrank.com/) ( 👔 )
161 | - [kaggle.com](https://www.kaggle.com/) ( 🧠 )
162 | - [leetcode.com](https://leetcode.com/) ( 👔 )
163 | - [projecteuler.net](https://projecteuler.net/)
164 | - [replit.com](https://replit.com/)
165 | - [w3schools.com](https://www.w3schools.com/python/) ( 🧪 )
166 |
--------------------------------------------------------------------------------
/README.es.md:
--------------------------------------------------------------------------------
1 | # Guía de estudio "Python Definitivo"
2 |
3 | [](https://github.com/huangsam/ultimate-python/actions)
4 | [](https://codecov.io/gh/huangsam/ultimate-python)
5 | [](https://sonarcloud.io/dashboard?id=huangsam_ultimate-python)
6 | [](https://github.com/huangsam/ultimate-python/blob/main/LICENSE)
7 | [](https://www.reddit.com/r/Python/comments/inllmf/ultimate_python_study_guide/)
8 |
9 | Guía de estudio "Python Definitivo" para principiantes y profesionales. 🐍 🐍 🐍
10 |
11 | ```python
12 | print("Guía de estudio 'Python Definitivo'")
13 | ```
14 |
15 | [English](README.md) |
16 | [한국어](README.ko.md) |
17 | [繁体中文](README.zh_tw.md) |
18 | [Español](README.es.md) |
19 | [Deutsch](README.de.md) |
20 | [हिन्दी](README.hi.md)
21 |
22 |
23 |
24 | ## Motivación
25 |
26 | Creé este repositorio de GitHub para compartir lo que he aprendido sobre [Python](https://www.python.org/)
27 | durante más de 5 años usándolo como graduado de universidad, empleado en grandes empresas y como contribuidor
28 | de código abierto en repositorios como [Celery](https://github.com/celery/celery) y
29 | [Full Stack Python](https://github.com/mattmakai/fullstackpython.com).
30 | Espero ver a más personas aprendiendo Python y persiguiendo su pasión a través de él. 🎓
31 |
32 | ## Objetivos
33 |
34 | Estos son los objetivos principales de esta guía:
35 |
36 | 🏆 **Servir como un recurso** para principiantes de Python que prefieren aprender por su cuenta.
37 | Este repositorio enumera una colección de módulos independientes que pueden ser ejecutados en
38 | un IDE como [PyCharm](https://www.jetbrains.com/pycharm/) e incluso en el navegador, como
39 | [Repl.it](https://repl.it/languages/python3). Incluso una terminal antigua funcionará igual de bien
40 | con los ejemplos. La mayoría de las líneas de código tienen comentarios útiles que ayudan a guiar
41 | al lector para entender paso a paso el proceso que el programa está ejecutando. Se anima a los usuarios
42 | a que modifiquen el código fuente en cualquier parte siempre y cuando las rutinas principales (`main`)
43 | se eliminen y se [ejecuten con éxito](runner.py) tras cada cambio.
44 |
45 | 🏆 **Servir como una guía pura** para aquellos que quieren reforzar los conceptos base de
46 | Python. Se utilizan sólo las [librerías integradas](https://docs.python.org/3/library/) para que
47 | estos conceptos puedan adquirirse sin el esfuerzo de aprender conocimientos de dominios específicos.
48 | Por ello no se han instalado librerías y entornos de código abierto populares (como `sqlalchemy`,
49 | `requests`, `pandas`). No obstante, leer el código fuente de estos frameworks es inspirador y altamente
50 | recomendado si tu objetivo es convertirte en un verdadero
51 | [Pythonista](https://www.urbandictionary.com/define.php?term=pythonista).
52 |
53 | ## Empezando
54 |
55 | [](https://repl.it/github/huangsam/ultimate-python)
56 |
57 | Haz clic en la imagen de arriba para crear un ambiente de trabajo en el navegador sin necesidad
58 | de tener Git y Python instalados en tu ordenador local. Si estos requisitos ya se cumplen,
59 | puedes clonar el repositorio directamente.
60 |
61 | Una vez que el repositorio sea accesible, estás listo para aprender de los módulos independientes.
62 | Para aprender el máximo de cada módulo, lee el código del módulo y ejecútalo.
63 | Hay dos maneras de ejecutar los módulos:
64 |
65 | 1. Ejecuta un solo módulo: `python ultimatepython/syntax/variable.py`
66 | 2. Ejecuta todos los módulos: `python runner.py`
67 |
68 | ## Contenido
69 |
70 | 📚 = Recurso externo,
71 | 🍰 = Tema principiante,
72 | 🤯 = Tema avanzado
73 |
74 | 1. **Sobre Python**
75 | - Resumen: [¿Qué es Python?](https://github.com/trekhleb/learn-python/blob/master/src/getting_started/what_is_python.md) ( 📚, 🍰 )
76 | - Filosofía de diseño: [El Zen de Python](https://www.python.org/dev/peps/pep-0020/) ( 📚 )
77 | - Guía de estilos: [Guía de estilos para código de Python](https://www.python.org/dev/peps/pep-0008/) ( 📚, 🤯 )
78 | - Modelo de datos: [Modelo de datos](https://docs.python.org/3/reference/datamodel.html) ( 📚, 🤯 )
79 | - Librería estándar: [La librería estándar de Python](https://docs.python.org/3/library/) ( 📚, 🤯 )
80 | - Funciones integradas: [Funciones integradas](https://docs.python.org/3/library/functions.html) ( 📚 )
81 | 2. **Sintaxis**
82 | - Variables: [Literales integrados](ultimatepython/syntax/variable.py) ( 🍰 )
83 | - Expresiones: [Operaciones numéricas](ultimatepython/syntax/expression.py) ( 🍰 )
84 | - Bit a bit: [Operadores bit a bit](ultimatepython/syntax/bitwise.py) ( 🍰 ), [Complemento a uno/dos](https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/) ( 📚 )
85 | - Condicionales: [if | if-else | if-elif-else](ultimatepython/syntax/conditional.py) ( 🍰 )
86 | - Iteraciones: [for-loop | while-loop](ultimatepython/syntax/loop.py) ( 🍰 )
87 | - Funciones: [def | lambda](ultimatepython/syntax/function.py) ( 🍰 )
88 | 3. **Estructura de datos**
89 | - Lista: [Operaciones con listas](ultimatepython/data_structures/list.py) ( 🍰 )
90 | - Tupla: [Operaciones con tuplas](ultimatepython/data_structures/tuple.py)
91 | - Set: [Operaciones con sets](ultimatepython/data_structures/set.py)
92 | - Diccionario: [Operaciones con dicts](ultimatepython/data_structures/dict.py) ( 🍰 )
93 | - Comprensión: [list | tuple | set | dict](ultimatepython/data_structures/comprehension.py)
94 | - Cadena: [Operaciones con strings](ultimatepython/data_structures/string.py) ( 🍰 )
95 | - Deque: [deque](ultimatepython/data_structures/deque.py) ( 🤯 )
96 | - Namedtuple: [namedtuple](ultimatepython/data_structures/namedtuple.py) ( 🤯 )
97 | - Defaultdict: [defaultdict](ultimatepython/data_structures/defaultdict.py) ( 🤯 )
98 | - Complejidad de tiempo: [Operaciones de cPython](https://wiki.python.org/moin/TimeComplexity) ( 📚, 🤯 )
99 | 4. **Clases**
100 | - Clase básica: [Definición de básica](ultimatepython/classes/basic_class.py) ( 🍰 )
101 | - Herencia: [Herencia](ultimatepython/classes/inheritance.py) ( 🍰 )
102 | - Clase abstracta: [Definición de abstracta](ultimatepython/classes/abstract_class.py)
103 | - Clase de excepción: [Definición de excepción](ultimatepython/classes/exception_class.py)
104 | - Clase iteradora: [Definición de iteradora | yield](ultimatepython/classes/iterator_class.py) ( 🤯 )
105 | - Encapsulación: [Definición de encapsulación](ultimatepython/classes/encapsulation.py)
106 | 5. **Avanzado**
107 | - Decorador: [Definición de decorador | wraps](ultimatepython/advanced/decorator.py) ( 🤯 )
108 | - Manejo de archivos: [Manejo de archivos](ultimatepython/advanced/file_handling.py) ( 🤯 )
109 | - Gestor de contexto: [Gestores de contexto](ultimatepython/advanced/context_manager.py) ( 🤯 )
110 | - Orden de resolución de método (MRO por sus siglas en inglés): [mro](ultimatepython/advanced/mro.py) ( 🤯 )
111 | - Mixin: [Definición de Mixin](ultimatepython/advanced/mixin.py) ( 🤯 )
112 | - Metaclase: [Definición de metaclase](ultimatepython/advanced/meta_class.py) ( 🤯 )
113 | - Hilos: [ThreadPoolExecutor](ultimatepython/advanced/thread.py) ( 🤯 )
114 | - Asyncio: [async | await](ultimatepython/advanced/async.py) ( 🤯 )
115 | - Referencias débiles: [weakref](ultimatepython/advanced/weak_ref.py) ( 🤯 )
116 | - Referencia: [cProfile | pstats](ultimatepython/advanced/benchmark.py) ( 🤯 )
117 | - Mocking: [MagicMock | PropertyMock | patch](ultimatepython/advanced/mocking.py) ( 🤯 )
118 | - Expresiones regulares: [search | findall | match | fullmatch](ultimatepython/advanced/regex.py) ( 🤯 )
119 | - Formatos de datos: [json | xml | csv](ultimatepython/advanced/data_format.py) ( 🤯 )
120 | - Fecha y hora: [datetime | timezone](ultimatepython/advanced/date_time.py) ( 🤯 )
121 |
122 | ## Recursos adicionales
123 |
124 | 👔 = Recurso de entrevista,
125 | 🧪 = Ejemplos de código,
126 | 🧠 = Ideas para proyecto
127 |
128 | ### Repositorios de GitHub
129 |
130 | Sigue aprendiendo leyendo otros buenos recursos.
131 |
132 | - [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) ( 👔, 🧪 )
133 | - [faif/python-patterns](https://github.com/faif/python-patterns) ( 👔, 🧪 )
134 | - [geekcomputers/Python](https://github.com/geekcomputers/Python) ( 🧪 )
135 | - [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) ( 🧪 )
136 | - [karan/Projects](https://github.com/karan/Projects) (🧠 )
137 | - [MunGell/awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) ( 🧠 )
138 | - [vinta/awesome-python](https://github.com/vinta/awesome-python)
139 | - [academic/awesome-datascience](https://github.com/academic/awesome-datascience)
140 | - [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
141 | - [ZuzooVn/machine-learning-for-software-engineers](https://github.com/ZuzooVn/machine-learning-for-software-engineers)
142 | - [30-seconds/30-seconds-of-python](https://github.com/30-seconds/30-seconds-of-python) ( 🧪 )
143 | - [ml-tooling/best-of-python](https://github.com/ml-tooling/best-of-python)
144 | - [practical-tutorials/project-based-learning](https://github.com/practical-tutorials/project-based-learning#python)
145 | - [freeCodeCamp/freeCodeCamp](https://github.com/freeCodeCamp/freeCodeCamp) ( 👔 )
146 |
147 | ### Práctica interactiva
148 |
149 | Continua practicando para que no se oxiden tus habilidades de programación.
150 |
151 | - [codechef.com](https://www.codechef.com/) ( 👔 )
152 | - [codeforces.com](https://codeforces.com/)
153 | - [codementor.io](https://www.codementor.io) ( 🧠 )
154 | - [coderbyte.com](https://www.coderbyte.com/) ( 👔 )
155 | - [codewars.com](https://www.codewars.com/)
156 | - [exercism.io](https://exercism.io/)
157 | - [geeksforgeeks.org](https://www.geeksforgeeks.org/) ( 👔 )
158 | - [hackerearth.com](https://www.hackerearth.com/)
159 | - [hackerrank.com](https://www.hackerrank.com/) ( 👔 )
160 | - [kaggle.com](https://www.kaggle.com/) ( 🧠 )
161 | - [leetcode.com](https://leetcode.com/) ( 👔 )
162 | - [projecteuler.net](https://projecteuler.net/)
163 | - [replit.com](https://replit.com/)
164 | - [w3schools.com](https://www.w3schools.com/python/) ( 🧪 )
165 |
--------------------------------------------------------------------------------
/README.hi.md:
--------------------------------------------------------------------------------
1 | # अल्टीमेट Python अध्ययन गाइड
2 |
3 | [](https://github.com/huangsam/ultimate-python/actions)
4 | [](https://codecov.io/gh/huangsam/ultimate-python)
5 | [](https://sonarcloud.io/dashboard?id=huangsam_ultimate-python)
6 | [](https://github.com/huangsam/ultimate-python/blob/main/LICENSE)
7 | [](https://www.reddit.com/r/Python/comments/inllmf/ultimate_python_study_guide/)
8 |
9 | नए और पेशेवर लोगों के लिए अल्टीमेट पायथन अध्ययन गाइड। 🐍 🐍 🐍
10 |
11 | ```python
12 | print("Ultimate Python study guide")
13 | ```
14 |
15 | [English](README.md) |
16 | [한국어](README.ko.md) |
17 | [繁体中文](README.zh_tw.md) |
18 | [Español](README.es.md) |
19 | [Deutsch](README.de.md) |
20 | [हिन्दी](README.hi.md)
21 |
22 |
23 |
24 | ## प्रेरणा
25 |
26 | मैंने यह गिटहब रिपोजिटरी [core Python](https://www.python.org/) के बारे में जो कुछ मैंने पिछले 5+ वर्षों में सीखा है, उसे साझा करने के लिए बनाई है। मैंने इसे एक कॉलेज ग्रेजुएट, बड़ी कंपनियों के कर्मचारी, और [Celery](https://github.com/celery/celery) और [Full Stack Python](https://github.com/mattmakai/fullstackpython.com) जैसी रिपोजिटरी के ओपन-सोर्स कंट्रीब्यूटर के रूप में उपयोग किया है। मैं यह देखने के लिए उत्सुक हूँ कि और लोग पायथन सीखें और इसके माध्यम से अपने जुनून को आगे बढ़ाएं। 🎓
27 |
28 |
29 | ## लक्ष्य
30 |
31 | इस गाइड को बनाने के मुख्य लक्ष्य निम्नलिखित हैं:
32 |
33 | 🏆 **संसाधन के रूप में सेवा देना** उन नए पायथन उपयोगकर्ताओं के लिए जो प्रैक्टिकल तरीके से सीखना पसंद करते हैं। इस रिपोजिटरी में स्वतंत्र मॉड्यूलों का एक संग्रह है, जिन्हें IDE जैसे [PyCharm](https://www.jetbrains.com/pycharm/) में या [Replit](https://replit.com/languages/python3) जैसे ब्राउज़र में चलाया जा सकता है। पुराने साधारण टर्मिनल में भी इन उदाहरणों को चलाया जा सकता है। अधिकतर लाइनों में बहुत ही अच्छे से लिखे गए comments होते हैं, जो पाठक को प्रोग्राम्स के प्रत्येक चरण के माध्यम से मार्गदर्शन करते हैं। उपयोगकर्ताओं को कोड में बदलाव करने के लिए प्रोत्साहित किया जाता है, बशर्ते कि `main` रूटीन को हटाया न जाए और हर परिवर्तन के बाद [सफलतापूर्वक चलाया जाए](runner.py)।
34 |
35 | 🏆 **शुद्ध गाइड के रूप में सेवा देना** उन लोगों के लिए जो मुख्य पायथन अवधारणाओं को फिर से समझना चाहते हैं। केवल [बिल्ट-इन लाइब्रेरीज़](https://docs.python.org/3/library/) का उपयोग किया गया है ताकि इन अवधारणाओं को बिना किसी विशेष डोमेन की अवधारणाओं के सरलता से समझाया जा सके। इसी कारण से लोकप्रिय ओपन-सोर्स लाइब्रेरीज़ और फ्रेमवर्क (जैसे `sqlalchemy`, `requests`, `pandas`) को इंस्टॉल नहीं किया गया है। हालांकि, इन फ्रेमवर्क्स के स्रोत कोड को पढ़ना प्रेरणादायक है और यदि आपका लक्ष्य एक सच्चे [Pythonista](https://www.urbandictionary.com/define.php?term=pythonista) बनने का है तो इसे ज़रूर पढ़ना चाहिए।
36 |
37 |
38 | ## शुरूआत
39 |
40 | [](https://replit.com/github/huangsam/ultimate-python)
41 |
42 | ऊपर दिए गए बैज पर क्लिक करें ताकि आप ब्राउज़र में एक कार्यशील वातावरण शुरू कर सकें, इसके लिए आपके स्थानीय मशीन पर Git और पायथन की आवश्यकता नहीं होगी। यदि ये आवश्यकताएँ पहले से ही पूरी हो चुकी हैं, तो आप सीधे रिपोजिटरी को क्लोन कर सकते हैं।
43 |
44 | एक बार जब रिपोजिटरी उपलब्ध हो जाती है, तो आप स्वतंत्र मॉड्यूल से सीखने के लिए तैयार हैं। प्रत्येक मॉड्यूल का अधिकतम लाभ उठाने के लिए, मॉड्यूल का कोड पढ़ें और इसे चलाएं। मॉड्यूल चलाने के दो तरीके हैं:
45 |
46 | 1. एकल मॉड्यूल चलाएं: `python ultimatepython/syntax/variable.py`
47 | 2. सभी मॉड्यूल चलाएं: `python runner.py`
48 |
49 | ## विषय सूची
50 |
51 | 📚 = बाहरी स्रोत,
52 | 🍰 = शुरुआती विषय,
53 | 🤯 = उन्नत विषय
54 |
55 |
56 | 1. **पायथन के बारे में**
57 | - अवलोकन: [पायथन क्या है](https://github.com/trekhleb/learn-python/blob/master/src/getting_started/what_is_python.md) ( 📚, 🍰 )
58 | - डिज़ाइन दर्शन: [पायथन का ज़ेन](https://www.python.org/dev/peps/pep-0020/) ( 📚 )
59 | - शैली मार्गदर्शिका: [पायथन कोड के लिए शैली मार्गदर्शिका](https://www.python.org/dev/peps/pep-0008/) ( 📚, 🤯 )
60 | - डेटा मॉडल: [डेटा मॉडल](https://docs.python.org/3/reference/datamodel.html) ( 📚, 🤯 )
61 | - मानक पुस्तकालय: [पायथन मानक पुस्तकालय](https://docs.python.org/3/library/) ( 📚, 🤯 )
62 | - अंतर्निहित कार्य: [अंतर्निहित कार्य](https://docs.python.org/3/library/functions.html) ( 📚 )
63 | 2. **सिंटेक्स**
64 | - वेरिएबल: [अंतर्निहित लिटरल](ultimatepython/syntax/variable.py) ( 🍰 )
65 | - अभिव्यक्ति: [संख्यात्मक ऑपरेशन्स](ultimatepython/syntax/expression.py) ( 🍰 )
66 | - बाइनरी: [बाइनरी ऑपरेटर](ultimatepython/syntax/bitwise.py) ( 🍰 ), [एक्स/टू का पूरक](https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/) ( 📚 )
67 | - कंडीशनल: [if | if-else | if-elif-else](ultimatepython/syntax/conditional.py) ( 🍰 )
68 | - लूप: [for-loop | while-loop](ultimatepython/syntax/loop.py) ( 🍰 )
69 | - फ़ंक्शन: [def | lambda](ultimatepython/syntax/function.py) ( 🍰 )
70 | 3. **डेटा संरचनाएँ**
71 | - लिसट: [लिसट ऑपरेशन्स](ultimatepython/data_structures/list.py) ( 🍰 )
72 | - ट्यूपल: [ट्यूपल ऑपरेशन्स](ultimatepython/data_structures/tuple.py)
73 | - सेट: [सेट ऑपरेशन्स](ultimatepython/data_structures/set.py)
74 | - डिक्ट: [डिक्शनरी ऑपरेशन्स](ultimatepython/data_structures/dict.py) ( 🍰 )
75 | - संकलन: [लिसट | ट्यूपल | सेट | डिक्ट](ultimatepython/data_structures/comprehension.py)
76 | - स्ट्रिंग: [स्ट्रिंग ऑपरेशन्स](ultimatepython/data_structures/string.py) ( 🍰 )
77 | - डेक: [डेक](ultimatepython/data_structures/deque.py) ( 🤯 )
78 | - नामित ट्यूपल: [नामित ट्यूपल](ultimatepython/data_structures/namedtuple.py) ( 🤯 )
79 | - डिफ़ॉल्ट डिक्ट: [डिफ़ॉल्ट डिक्ट](ultimatepython/data_structures/defaultdict.py) ( 🤯 )
80 | - समय कोम्पलेक्सिटी: [cPython ऑपरेशन्स](https://wiki.python.org/moin/TimeComplexity) ( 📚, 🤯 )
81 | 4. **क्लासेज़**
82 | - बेसिक क्लास: [बेसिक परिभाषा](ultimatepython/classes/basic_class.py) ( 🍰 )
83 | - इन्हरिटैंस: [इन्हरिटैंस](ultimatepython/classes/inheritance.py) ( 🍰 )
84 | - एैबस्टराक्ट क्लास: [एैबस्टराक्ट परिभाषा](ultimatepython/classes/abstract_class.py)
85 | - एक्सेपशन क्लास: [एक्सेपशन परिभाषा](ultimatepython/classes/exception_class.py)
86 | - इटरेटर क्लास: [इटरेटर परिभाषा | yield](ultimatepython/classes/iterator_class.py) ( 🤯 )
87 | - ऐनकैपसुलेषन: [ऐनकैपसुलेषन परिभाषा](ultimatepython/classes/encapsulation.py)
88 | 5. **उन्नत**
89 | - डेकोरेटर: [डेकोरेटर परिभाषा | wraps](ultimatepython/advanced/decorator.py) ( 🤯 )
90 | - फ़ाइल प्रबंधन: [फ़ाइल प्रबंधन](ultimatepython/advanced/file_handling.py) ( 🤯 )
91 | - संदर्भ प्रबंधक: [संदर्भ प्रबंधक](ultimatepython/advanced/context_manager.py) ( 🤯 )
92 | - मेथड रिज़ॉल्यूशन क्रम: [mro](ultimatepython/advanced/mro.py) ( 🤯 )
93 | - मिक्सिन: [मिक्सिन परिभाषा](ultimatepython/advanced/mixin.py) ( 🤯 )
94 | - मेटाक्लास: [मेटाक्लास परिभाषा](ultimatepython/advanced/meta_class.py) ( 🤯 )
95 | - थ्रेड: [ThreadPoolExecutor](ultimatepython/advanced/thread.py) ( 🤯 )
96 | - एसिंको: [async | await](ultimatepython/advanced/async.py) ( 🤯 )
97 | - वीक रेफरेंस: [weakref](ultimatepython/advanced/weak_ref.py) ( 🤯 )
98 | - बेंचमार्क: [cProfile | pstats](ultimatepython/advanced/benchmark.py) ( 🤯 )
99 | - मॉकिंग: [MagicMock | PropertyMock | patch](ultimatepython/advanced/mocking.py) ( 🤯 )
100 | - नियमित अभिव्यक्ति: [search | findall | match | fullmatch](ultimatepython/advanced/regex.py) ( 🤯 )
101 | - डेटा फ़ॉर्मेट: [json | xml | csv](ultimatepython/advanced/data_format.py) ( 🤯 )
102 | - दिनांक और समय: [datetime | timezone](ultimatepython/advanced/date_time.py) ( 🤯 )
103 |
104 |
105 | ## अतिरिक्त संसाधन
106 |
107 | 👔 = इंटरव्यू संसाधन,
108 | 🧪 = कोड नमूने,
109 | 🧠 = प्रोजेक्ट विचार
110 |
111 |
112 | ### गिटहब रिपॉजिटरी
113 |
114 | अन्य उच्च मानक संसाधनों से पढ़कर सीखना जारी रखें।
115 |
116 | - [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) ( 👔 , 🧪 )
117 | - [faif/python-patterns](https://github.com/faif/python-patterns) ( 👔 , 🧪 )
118 | - [geekcomputers/Python](https://github.com/geekcomputers/Python) ( 🧪 )
119 | - [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) ( 🧪 )
120 | - [karan/Projects](https://github.com/karan/Projects) ( 🧠 )
121 | - [MunGell/awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) ( 🧠 )
122 | - [vinta/awesome-python](https://github.com/vinta/awesome-python)
123 | - [academic/awesome-datascience](https://github.com/academic/awesome-datascience)
124 | - [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
125 | - [ZuzooVn/machine-learning-for-software-engineers](https://github.com/ZuzooVn/machine-learning-for-software-engineers)
126 | - [30-seconds/30-seconds-of-python](https://github.com/30-seconds/30-seconds-of-python) ( 🧪 )
127 | - [ml-tooling/best-of-python](https://github.com/ml-tooling/best-of-python)
128 | - [practical-tutorials/project-based-learning](https://github.com/practical-tutorials/project-based-learning#python)
129 | - [freeCodeCamp/freeCodeCamp](https://github.com/freeCodeCamp/freeCodeCamp) ( 👔 )
130 |
131 | ### इंटरैक्टिव प्रैक्टिस
132 |
133 | अभ्यास करते रहें ताकि आपकी कोडिंग कौशल खराब न हों।
134 |
135 | - [codechef.com](https://www.codechef.com/) ( 👔 )
136 | - [codeforces.com](https://codeforces.com/)
137 | - [codementor.io](https://www.codementor.io) ( 🧠 )
138 | - [coderbyte.com](https://www.coderbyte.com/) ( 👔 )
139 | - [codewars.com](https://www.codewars.com/)
140 | - [exercism.io](https://exercism.io/)
141 | - [geeksforgeeks.org](https://www.geeksforgeeks.org/) ( 👔 )
142 | - [hackerearth.com](https://www.hackerearth.com/)
143 | - [hackerrank.com](https://www.hackerrank.com/) ( 👔 )
144 | - [kaggle.com](https://www.kaggle.com/) ( 🧠 )
145 | - [leetcode.com](https://leetcode.com/) ( 👔 )
146 | - [projecteuler.net](https://projecteuler.net/)
147 | - [replit.com](https://replit.com/)
148 | - [w3schools.com](https://www.w3schools.com/python/) ( 🧪 )
149 |
--------------------------------------------------------------------------------
/README.ko.md:
--------------------------------------------------------------------------------
1 | # Ultimate Python 학습 가이드
2 |
3 | [](https://github.com/huangsam/ultimate-python/actions)
4 | [](https://codecov.io/gh/huangsam/ultimate-python)
5 | [](https://sonarcloud.io/dashboard?id=huangsam_ultimate-python)
6 | [](https://github.com/huangsam/ultimate-python/blob/main/LICENSE)
7 | [](https://www.reddit.com/r/Python/comments/inllmf/ultimate_python_study_guide/)
8 |
9 | 초보자와 전문가 모두를 위한 최고의 Python 학습 가이드입니다. 🐍 🐍 🐍
10 |
11 | ```python
12 | print("Ultimate Python 학습 가이드")
13 | ```
14 |
15 | [English](README.md) |
16 | [한국어](README.ko.md) |
17 | [繁体中文](README.zh_tw.md) |
18 | [Español](README.es.md) |
19 | [Deutsch](README.de.md) |
20 | [हिन्दी](README.hi.md)
21 |
22 |
23 |
24 | ## 동기
25 |
26 | 이 GitHub 저장소는 대학 졸업 후, 대규모 회사에서 근무하면서
27 | 그리고 [Celery](https://github.com/celery/celery)와 [Full Stack Python](https://github.com/mattmakai/fullstackpython.com) 같은 오픈소스 프로젝트에 기여하면서
28 | 지난 5년 이상 동안 배운 [core Python](https://www.python.org/)에 대한 지식을 공유하기 위해 만들었습니다.
29 | 저는 더 많은 사람들이 Python을 배우고 자신의 열정을 추구하길 기대합니다. 🎓
30 |
31 | ## 목표
32 |
33 | 이 가이드를 만드는 주요 목표는 다음과 같습니다:
34 |
35 | 🏆 실습 학습을 선호하는 Python 초보자를 위한 **학습 자료를 제공합니다.**
36 | 이 저장소에는 [PyCharm](https://www.jetbrains.com/pycharm/)과 같은 IDE 및 [Replit](https://replit.com/languages/python3)와 같은 브라우저에서 실행할 수 있는 독립형 모듈 모음이 있습니다. 기본 터미널에서도 예제를 실행할 수 있습니다.
37 | 대부분의 코드 라인에 프로그램이 단계별로 어떤 작업을 하는지 안내하는 신중하게 작성된 주석이 있습니다.
38 | 사용자는 `main` 루틴을 삭제하지 않고, 각 변경 후에 [성공적으로 실행](runner.py)되는 한 소스 코드를 얼마든지 수정할 수 있습니다.
39 |
40 | 🏆 core Python 개념을 다시 복습하고 싶은 사람들을 위한 **순수 가이드를 제공합니다.**
41 | 여기서는 오직 [내장 라이브러리](https://docs.python.org/3/library/)만을 사용하여 이러한 개념을 도메인 특화된 개념의 오버헤드 없이 전달합니다.
42 | 따라서 유명한 오픈소스 라이브러리와 프레임워크(`sqlalchemy`, `requests`, `pandas` 등)는 설치되어 있지 않습니다.
43 | 그러나, 당신의 목표가 진정한 진정한 [Pythonista](https://www.urbandictionary.com/define.php?term=pythonista)이 되는 것 이라면 이러한 프레임워크의 소스 코드를 읽는 것은 매우 고무적이고 권장이 됩니다.
44 |
45 | ## 시작하기
46 |
47 | [](https://repl.it/github/huangsam/ultimate-python)
48 |
49 | 로컬 컴퓨터에 Git 및 Python을 설치하지 않고도 브라우저에서 작업 환경을 시작하려면 위의 배지를 클릭하세요. 이러한
50 | 요구 사항이 이미 충족된 경우, 저장소를 바로 clone해도 됩니다.
51 |
52 | 저장소에 접근할 수 있게 되면 단독 모듈에서 배울 준비가 된 것입니다. 각 모듈을 최대한 활용하려면 모듈 코드를
53 | 읽고 실행하십시오. 모듈을 실행하는 두 가지 방법이 있습니다:
54 |
55 | 1. 단일 모듈 실행 : `python ultimatepython/syntax/variable.py`
56 | 2. 전체 모듈 실행 : `python runner.py`
57 |
58 | ## 목차
59 |
60 | 📚 = 외부 리소스,
61 | 🍰 = 초급 주제,
62 | 🤯 = 고급 주제
63 |
64 | 1. **Python 정보**
65 | - 개요 : [Python이란 무엇인가](https://github.com/trekhleb/learn-python/blob/master/src/getting_started/what_is_python.md) ( 📚, 🍰 )
66 | - 디자인 철학 : [The Zen of Python](https://www.python.org/dev/peps/pep-0020/) ( 📚 )
67 | - 스타일 가이드 : [Python 코드 스타일 가이드](https://www.python.org/dev/peps/pep-0008/) ( 📚, 🤯 )
68 | - 데이터 모델 : [데이터 모델](https://docs.python.org/3/reference/datamodel.html) ( 📚, 🤯 )
69 | - 표준 라이브러리 : [Python 표준 라이브러리](https://docs.python.org/3/library/) ( 📚, 🤯 )
70 | - 내장 함수 : [내장 함수](https://docs.python.org/3/library/functions.html) ( 📚 )
71 | 2. **통사론**
72 | - 변수 : [내장 리터럴](ultimatepython/syntax/variable.py) ( 🍰 )
73 | - 표현식 : [숫자 연산](ultimatepython/syntax/expression.py) ( 🍰 )
74 | - 비트 연산 : [비트 연산자](ultimatepython/syntax/bitwise.py) ( 🍰 ), [1의 보수/2의 보수](https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/) ( 📚 )
75 | - 조건문 : [if | if-else | if-elif-else](ultimatepython/syntax/conditional.py) ( 🍰 )
76 | - 반복문 : [for-loop | while-loop](ultimatepython/syntax/loop.py) ( 🍰 )
77 | - 함수 : [def | lambda](ultimatepython/syntax/function.py) ( 🍰 )
78 | 3. **데이터 구조**
79 | - 리스트 : [리스트 연산](ultimatepython/data_structures/list.py) ( 🍰 )
80 | - 튜플 : [튜플 연산](ultimatepython/data_structures/tuple.py)
81 | - 세트 : [세트 연산](ultimatepython/data_structures/set.py)
82 | - 딕셔너리 : [딕셔너리 연산](ultimatepython/data_structures/dict.py) ( 🍰 )
83 | - 컴프리헨션 : [리스트 | 튜플 | 세트 | 딕셔너리](ultimatepython/data_structures/comprehension.py)
84 | - 문자열 : [문자열 연산](ultimatepython/data_structures/string.py) ( 🍰 )
85 | - 덱: [deque](ultimatepython/data_structures/deque.py) ( 🤯 )
86 | - Namedtuple: [namedtuple](ultimatepython/data_structures/namedtuple.py) ( 🤯 )
87 | - Defaultdict: [defaultdict](ultimatepython/data_structures/defaultdict.py) ( 🤯 )
88 | - 시간 복잡도 : [cPython 연산](https://wiki.python.org/moin/TimeComplexity) ( 📚, 🤯 )
89 | 4. **클래스**
90 | - 기본 클래스 : [기본 정의](ultimatepython/classes/basic_class.py) ( 🍰 )
91 | - 계승: [계승](ultimatepython/classes/inheritance.py) ( 🍰 )
92 | - 추상 클래스 : [추상 정의](ultimatepython/classes/abstract_class.py)
93 | - 예외 클래스 : [예외 정의](ultimatepython/classes/exception_class.py)
94 | - 이터레이터 클래스 : [이터레이터 정의 | yield](ultimatepython/classes/iterator_class.py) ( 🤯 )
95 | - 캡슐화: [캡슐화 정의](ultimatepython/classes/encapsulation.py)
96 | 5. **고급**
97 | - 데코레이터 : [데코레이터 정의 | wraps](ultimatepython/advanced/decorator.py) ( 🤯 )
98 | - 파일 처리: [파일 처리](ultimatepython/advanced/file_handling.py) ( 🤯 )
99 | - 컨텍스트 매니저 : [컨텍스트 매니저](ultimatepython/advanced/context_manager.py) ( 🤯 )
100 | - 메서드 결정 순서 : [mro](ultimatepython/advanced/mro.py) ( 🤯 )
101 | - 믹스인 : [믹스인 정의](ultimatepython/advanced/mixin.py) ( 🤯 )
102 | - 메타클래스 : [메타클래스 정의](ultimatepython/advanced/meta_class.py) ( 🤯 )
103 | - 스레드 : [ThreadPoolExecutor](ultimatepython/advanced/thread.py) ( 🤯 )
104 | - Asyncio : [async | await](ultimatepython/advanced/async.py) ( 🤯 )
105 | - 약한 참조 : [weakref](ultimatepython/advanced/weak_ref.py) ( 🤯 )
106 | - 벤치마크 : [cProfile | pstats](ultimatepython/advanced/benchmark.py) ( 🤯 )
107 | - 모킹 : [MagicMock | PropertyMock | patch](ultimatepython/advanced/mocking.py) ( 🤯 )
108 | - 정규식 : [search | findall | match | fullmatch](ultimatepython/advanced/regex.py) ( 🤯 )
109 | - 데이터 포맷 : [json | xml | csv](ultimatepython/advanced/data_format.py) ( 🤯 )
110 | - 날짜와 시간 : [datetime | timezone](ultimatepython/advanced/date_time.py) ( 🤯 )
111 |
112 | ## 추가 자료
113 |
114 | 👔 = 인터뷰 자료,
115 | 🧪 = 코드 샘플,
116 | 🧠 = 프로젝트 아이디어
117 |
118 | ### GitHub 저장소
119 |
120 | 잘 알려진 다른 자료를 읽으면서 계속 배우세요.
121 |
122 | - [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) ( 👔, 🧪 )
123 | - [faif/python-patterns](https://github.com/faif/python-patterns) ( 👔, 🧪 )
124 | - [geekcomputers/Python](https://github.com/geekcomputers/Python) ( 🧪 )
125 | - [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) ( 🧪 )
126 | - [karan/Projects](https://github.com/karan/Projects) ( 🧠 )
127 | - [MunGell/awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) ( 🧠 )
128 | - [vinta/awesome-python](https://github.com/vinta/awesome-python)
129 | - [academic/awesome-datascience](https://github.com/academic/awesome-datascience)
130 | - [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
131 | - [ZuzooVn/machine-learning-for-software-engineers](https://github.com/ZuzooVn/machine-learning-for-software-engineers)
132 | - [30-seconds/30-seconds-of-python](https://github.com/30-seconds/30-seconds-of-python) ( 🧪 )
133 | - [ml-tooling/best-of-python](https://github.com/ml-tooling/best-of-python)
134 | - [practical-tutorials/project-based-learning](https://github.com/practical-tutorials/project-based-learning#python)
135 | - [freeCodeCamp/freeCodeCamp](https://github.com/freeCodeCamp/freeCodeCamp) ( 👔 )
136 |
137 | ### 대화형 연습
138 |
139 | 코딩 실력이 녹슬지 않기 위해 계속 연습하세요.
140 |
141 | - [codechef.com](https://www.codechef.com/) ( 👔 )
142 | - [codeforces.com](https://codeforces.com/)
143 | - [codementor.io](https://www.codementor.io) ( 🧠 )
144 | - [coderbyte.com](https://www.coderbyte.com/) ( 👔 )
145 | - [codewars.com](https://www.codewars.com/)
146 | - [exercism.io](https://exercism.io/)
147 | - [geeksforgeeks.org](https://www.geeksforgeeks.org/) ( 👔 )
148 | - [hackerearth.com](https://www.hackerearth.com/)
149 | - [hackerrank.com](https://www.hackerrank.com/) ( 👔 )
150 | - [kaggle.com](https://www.kaggle.com/) ( 🧠 )
151 | - [leetcode.com](https://leetcode.com/) ( 👔 )
152 | - [projecteuler.net](https://projecteuler.net/)
153 | - [replit.com](https://replit.com/)
154 | - [w3schools.com](https://www.w3schools.com/python/) ( 🧪 )
155 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Ultimate Python study guide
2 |
3 | [](https://github.com/huangsam/ultimate-python/actions)
4 | [](https://codecov.io/gh/huangsam/ultimate-python)
5 | [](https://sonarcloud.io/dashboard?id=huangsam_ultimate-python)
6 | [](https://github.com/huangsam/ultimate-python/blob/main/LICENSE)
7 | [](https://www.reddit.com/r/Python/comments/inllmf/ultimate_python_study_guide/)
8 |
9 | Ultimate Python study guide for newcomers and professionals alike. 🐍 🐍 🐍
10 |
11 | ```python
12 | print("Ultimate Python study guide")
13 | ```
14 |
15 | [English](README.md) |
16 | [한국어](README.ko.md) |
17 | [繁体中文](README.zh_tw.md) |
18 | [Español](README.es.md) |
19 | [Deutsch](README.de.md) |
20 | [हिन्दी](README.hi.md)
21 |
22 |
23 |
24 | ## Motivation
25 |
26 | I created this GitHub repo to share what I've learned about [core Python](https://www.python.org/)
27 | over the past 5+ years of using it as a college graduate, an employee at
28 | large-scale companies and an open-source contributor of repositories like
29 | [Celery](https://github.com/celery/celery) and
30 | [Full Stack Python](https://github.com/mattmakai/fullstackpython.com).
31 | I look forward to seeing more people learn Python and pursue their passions
32 | through it. 🎓
33 |
34 | ## Goals
35 |
36 | Here are the primary goals of creating this guide:
37 |
38 | 🏆 **Serve as a resource** for Python newcomers who prefer to learn hands-on.
39 | This repository has a collection of standalone modules which can be run in an IDE
40 | like [PyCharm](https://www.jetbrains.com/pycharm/) and in the browser like
41 | [Replit](https://replit.com/languages/python3). Even a plain old terminal will work
42 | with the examples. Most lines have carefully crafted comments which guide a reader
43 | through what the programs are doing step-by-step. Users are encouraged to modify
44 | source code anywhere as long as the `main` routines are not deleted and
45 | [run successfully](runner.py) after each change.
46 |
47 | 🏆 **Serve as a pure guide** for those who want to revisit core Python concepts.
48 | Only [builtin libraries](https://docs.python.org/3/library/) are leveraged so that
49 | these concepts can be conveyed without the overhead of domain-specific concepts. As
50 | such, popular open-source libraries and frameworks (i.e. `sqlalchemy`, `requests`,
51 | `pandas`) are not installed. However, reading the source code in these frameworks is
52 | inspiring and highly encouraged if your goal is to become a true
53 | [Pythonista](https://www.urbandictionary.com/define.php?term=pythonista).
54 |
55 | ## Getting started
56 |
57 | [](https://replit.com/github/huangsam/ultimate-python)
58 |
59 | Click the badge above to spin up a working environment in the browser without
60 | needing Git and Python installed on your local machine. If these requirements
61 | are already met, feel free to clone the repository directly.
62 |
63 | Once the repository is accessible, you are ready to learn from the standalone
64 | modules. To get the most out of each module, read the module code and run it.
65 | There are two ways of running the modules:
66 |
67 | 1. Run a single module: `python ultimatepython/syntax/variable.py`
68 | 2. Run all of the modules: `python runner.py`
69 |
70 | ## Table of contents
71 |
72 | 📚 = External resource,
73 | 🍰 = Beginner topic,
74 | 🤯 = Advanced topic
75 |
76 | 1. **About Python**
77 | - Overview: [What is Python](https://github.com/trekhleb/learn-python/blob/master/src/getting_started/what_is_python.md) ( 📚, 🍰 )
78 | - Design philosophy: [The Zen of Python](https://www.python.org/dev/peps/pep-0020/) ( 📚 )
79 | - Style guide: [Style Guide for Python Code](https://www.python.org/dev/peps/pep-0008/) ( 📚, 🤯 )
80 | - Data model: [Data model](https://docs.python.org/3/reference/datamodel.html) ( 📚, 🤯 )
81 | - Standard library: [The Python Standard Library](https://docs.python.org/3/library/) ( 📚, 🤯 )
82 | - Built-in functions: [Built-in Functions](https://docs.python.org/3/library/functions.html) ( 📚 )
83 | 2. **Syntax**
84 | - Variable: [Built-in literals](ultimatepython/syntax/variable.py) ( 🍰 )
85 | - Expression: [Numeric operations](ultimatepython/syntax/expression.py) ( 🍰 )
86 | - Bitwise: [Bitwise operators](ultimatepython/syntax/bitwise.py) ( 🍰 ), [One's/Two's Complement](https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/) ( 📚 )
87 | - Conditional: [if | if-else | if-elif-else](ultimatepython/syntax/conditional.py) ( 🍰 )
88 | - Loop: [for-loop | while-loop](ultimatepython/syntax/loop.py) ( 🍰 )
89 | - Function: [def | lambda](ultimatepython/syntax/function.py) ( 🍰 )
90 | 3. **Data Structures**
91 | - List: [List operations](ultimatepython/data_structures/list.py) ( 🍰 )
92 | - Tuple: [Tuple operations](ultimatepython/data_structures/tuple.py)
93 | - Set: [Set operations](ultimatepython/data_structures/set.py)
94 | - Dict: [Dictionary operations](ultimatepython/data_structures/dict.py) ( 🍰 )
95 | - Comprehension: [list | tuple | set | dict](ultimatepython/data_structures/comprehension.py)
96 | - String: [String operations](ultimatepython/data_structures/string.py) ( 🍰 )
97 | - Deque: [deque](ultimatepython/data_structures/deque.py) ( 🤯 )
98 | - Namedtuple: [namedtuple](ultimatepython/data_structures/namedtuple.py) ( 🤯 )
99 | - Defaultdict: [defaultdict](ultimatepython/data_structures/defaultdict.py) ( 🤯 )
100 | - Time complexity: [cPython operations](https://wiki.python.org/moin/TimeComplexity) ( 📚, 🤯 )
101 | 4. **Classes**
102 | - Basic class: [Basic definition](ultimatepython/classes/basic_class.py) ( 🍰 )
103 | - Inheritance: [Inheritance](ultimatepython/classes/inheritance.py) ( 🍰 )
104 | - Abstract class: [Abstract definition](ultimatepython/classes/abstract_class.py)
105 | - Exception class: [Exception definition](ultimatepython/classes/exception_class.py)
106 | - Iterator class: [Iterator definition | yield](ultimatepython/classes/iterator_class.py) ( 🤯 )
107 | - Encapsulation: [Encapsulation definition](ultimatepython/classes/encapsulation.py)
108 | 5. **Advanced**
109 | - Decorator: [Decorator definition | wraps](ultimatepython/advanced/decorator.py) ( 🤯 )
110 | - File Handling: [File Handling](ultimatepython/advanced/file_handling.py) ( 🤯 )
111 | - Context manager: [Context managers](ultimatepython/advanced/context_manager.py) ( 🤯 )
112 | - Method resolution order: [mro](ultimatepython/advanced/mro.py) ( 🤯 )
113 | - Mixin: [Mixin definition](ultimatepython/advanced/mixin.py) ( 🤯 )
114 | - Metaclass: [Metaclass definition](ultimatepython/advanced/meta_class.py) ( 🤯 )
115 | - Thread: [ThreadPoolExecutor](ultimatepython/advanced/thread.py) ( 🤯 )
116 | - Asyncio: [async | await](ultimatepython/advanced/async.py) ( 🤯 )
117 | - Weak reference: [weakref](ultimatepython/advanced/weak_ref.py) ( 🤯 )
118 | - Benchmark: [cProfile | pstats](ultimatepython/advanced/benchmark.py) ( 🤯 )
119 | - Mocking: [MagicMock | PropertyMock | patch](ultimatepython/advanced/mocking.py) ( 🤯 )
120 | - Regular expression: [search | findall | match | fullmatch](ultimatepython/advanced/regex.py) ( 🤯 )
121 | - Data format: [json | xml | csv](ultimatepython/advanced/data_format.py) ( 🤯 )
122 | - Datetime: [datetime | timezone](ultimatepython/advanced/date_time.py) ( 🤯 )
123 |
124 | ## Additional resources
125 |
126 | 👔 = Interview resource,
127 | 🧪 = Code samples,
128 | 🧠 = Project ideas
129 |
130 | ### GitHub repositories
131 |
132 | Keep learning by reading from other well-regarded resources.
133 |
134 | - [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) ( 👔 , 🧪 )
135 | - [faif/python-patterns](https://github.com/faif/python-patterns) ( 👔 , 🧪 )
136 | - [geekcomputers/Python](https://github.com/geekcomputers/Python) ( 🧪 )
137 | - [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) ( 🧪 )
138 | - [karan/Projects](https://github.com/karan/Projects) ( 🧠 )
139 | - [MunGell/awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) ( 🧠 )
140 | - [vinta/awesome-python](https://github.com/vinta/awesome-python)
141 | - [academic/awesome-datascience](https://github.com/academic/awesome-datascience)
142 | - [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
143 | - [ZuzooVn/machine-learning-for-software-engineers](https://github.com/ZuzooVn/machine-learning-for-software-engineers)
144 | - [30-seconds/30-seconds-of-python](https://github.com/30-seconds/30-seconds-of-python) ( 🧪 )
145 | - [ml-tooling/best-of-python](https://github.com/ml-tooling/best-of-python)
146 | - [practical-tutorials/project-based-learning](https://github.com/practical-tutorials/project-based-learning#python)
147 | - [freeCodeCamp/freeCodeCamp](https://github.com/freeCodeCamp/freeCodeCamp) ( 👔 )
148 |
149 | ### Interactive practice
150 |
151 | Keep practicing so that your coding skills don't get rusty.
152 |
153 | - [codechef.com](https://www.codechef.com/) ( 👔 )
154 | - [codeforces.com](https://codeforces.com/)
155 | - [codementor.io](https://www.codementor.io) ( 🧠 )
156 | - [coderbyte.com](https://www.coderbyte.com/) ( 👔 )
157 | - [codewars.com](https://www.codewars.com/)
158 | - [exercism.io](https://exercism.io/)
159 | - [geeksforgeeks.org](https://www.geeksforgeeks.org/) ( 👔 )
160 | - [hackerearth.com](https://www.hackerearth.com/)
161 | - [hackerrank.com](https://www.hackerrank.com/) ( 👔 )
162 | - [kaggle.com](https://www.kaggle.com/) ( 🧠 )
163 | - [leetcode.com](https://leetcode.com/) ( 👔 )
164 | - [projecteuler.net](https://projecteuler.net/)
165 | - [replit.com](https://replit.com/)
166 | - [w3schools.com](https://www.w3schools.com/python/) ( 🧪 )
167 |
--------------------------------------------------------------------------------
/README.zh_tw.md:
--------------------------------------------------------------------------------
1 | # Ultimate Python 學習大綱
2 |
3 | [](https://github.com/huangsam/ultimate-python/actions)
4 | [](https://codecov.io/gh/huangsam/ultimate-python)
5 | [](https://sonarcloud.io/dashboard?id=huangsam_ultimate-python)
6 | [](https://github.com/huangsam/ultimate-python/blob/main/LICENSE)
7 | [](https://www.reddit.com/r/Python/comments/inllmf/ultimate_python_study_guide/)
8 |
9 | Ultimate Python 學習大綱 - 適用於新手和專業人士。🐍 🐍 🐍
10 |
11 | ```python
12 | print("Ultimate Python 學習大綱")
13 | ```
14 |
15 | [English](README.md) |
16 | [한국어](README.ko.md) |
17 | [繁体中文](README.zh_tw.md) |
18 | [Español](README.es.md) |
19 | [Deutsch](README.de.md) |
20 | [हिन्दी](README.hi.md)
21 |
22 |
23 |
24 | ## 動力
25 |
26 | 我為了分享過去五年作為一個學生,大公司員工,以及開源(例如 Celery 和 Full Stack Python)貢獻者所習得的知識而創
27 | 建了這個代碼倉庫。我期待更多人能抱持熱忱並開始一段與Python的美好旅程。🎓
28 |
29 | ## 目標
30 |
31 | 這是創建本指南的主要目標:
32 |
33 | 🏆 **為喜歡動手學習的Python新手提供資源。** 本存儲庫集合了不同題目的獨立模組範例,而每個模組可以獨立在普通
34 | 終端機(Terminal),IDE(如PyCharm)或者瀏覽器(如Repl.it)中運行。範例中的註解都經過精心編寫,引導讀者逐步了解程
35 | 式流程。在不刪除主例程(main)並在修改後成功運行大前題下,我鼓勵讀者修改源代碼作練習。
36 |
37 | 🏆 **為想重溫Python核心概念的程式員提供指南。** 本存儲庫主要借助內置庫(builtin libraries)作重溫工具,
38 | 故不需額外安裝開源庫(如`sqlalchemy`,`requests`,`pandas`)。但是,如果您的目標是成為一個真正的Python
39 | 達人(Pythonista),那麼我會鼓勵您閱讀這些源代碼,而激發靈感。
40 |
41 | ## 學習之旅
42 |
43 | [](https://repl.it/github/huangsam/ultimate-python)
44 |
45 | 單擊上面的徽章就可在瀏覽器中啟動工作環境,而無需在電腦上額外安裝Git和Python。當你完成啟動,請複製這存儲庫。
46 | 當你可以開啟你所複製存儲庫後,您就準備好Python學習之旅!善用每個模組,請細讀註解並嘗試運行模組代碼。
47 |
48 | 有兩種運行模組的方式:
49 |
50 | 1. 運行單一模組:`python ultimatepython/syntax/variable.py`
51 | 2. 運行所有模組:`python runner.py`
52 |
53 | ## 目錄
54 |
55 | 📚 = 外部資源,
56 | 🍰 = 入門題目,
57 | 🤯 = 進階題目
58 |
59 | 1. **關於 Python**
60 | - 概述:[什麼是 Python](https://github.com/trekhleb/learn-python/blob/master/src/getting_started/what_is_python.md) ( 📚, 🍰 )
61 | - 設計理念:[Python之格言](https://www.python.org/dev/peps/pep-0020/) ( 📚 )
62 | - 樣式指南:[Python代碼樣式指南](https://www.python.org/dev/peps/pep-0008/) ( 📚, 🤯 )
63 | - 數據模型:[數據模型](https://docs.python.org/3/reference/datamodel.html) ( 📚, 🤯 )
64 | - 標準庫:[Python標準庫](https://docs.python.org/3/library/) ( 📚, 🤯 )
65 | - 內置函式:[內置函式](https://docs.python.org/3/library/functions.html) ( 📚 )
66 | 2. **語法**
67 | - 變數:[內置值](ultimatepython/syntax/variable.py) ( 🍰 )
68 | - 運算式:[數值運算](ultimatepython/syntax/expression.py) ( 🍰 )
69 | - 按位: [中的位元運算符](ultimatepython/syntax/bitwise.py) ( 🍰 ), [一個的補語/補碼](https://www.geeksforgeeks.org/difference-between-1s-complement-representation-and-2s-complement-representation-technique/) ( 📚 )
70 | - 條件運算式:[if | if-else | if-elif-else](ultimatepython/syntax/conditional.py) ( 🍰 )
71 | - 迴圈:[for迴圈 | while迴圈](ultimatepython/syntax/loop.py) ( 🍰 )
72 | - 定義函式:[def | lambda](ultimatepython/syntax/function.py) ( 🍰 )
73 | 3. **資料結構**
74 | - 列表:[列表操作](ultimatepython/data_structures/list.py) ( 🍰 )
75 | - 元組:[元組操作](ultimatepython/data_structures/tuple.py)
76 | - 集合:[集合操作](ultimatepython/data_structures/set.py)
77 | - 字典:[字典操作](ultimatepython/data_structures/dict.py) ( 🍰 )
78 | - 綜合:[list | tuple | set | dict](ultimatepython/data_structures/comprehension.py)
79 | - 字串:[字串操作](ultimatepython/data_structures/string.py) ( 🍰 )
80 | - 雙端隊列:[deque](ultimatepython/data_structures/deque.py) ( 🤯 )
81 | - Namedtuple: [namedtuple](ultimatepython/data_structures/namedtuple.py) ( 🤯 )
82 | - Defaultdict: [defaultdict](ultimatepython/data_structures/defaultdict.py) ( 🤯 )
83 | - 時間複雜度:[cPython操作](https://wiki.python.org/moin/TimeComplexity) ( 📚, 🤯 )
84 | 4. **類別**
85 | - 基本類別:[基本定義](ultimatepython/classes/basic_class.py) ( 🍰 )
86 | - 抽象類別:[抽象定義](ultimatepython/classes/abstract_class.py)
87 | - 異常類別:[異常定義](ultimatepython/classes/exception_class.py)
88 | - 迭代類別:[迭代器定義](ultimatepython/classes/iterator_class.py) ( 🤯 )
89 | - 封裝: [封裝定義](ultimatepython/classes/encapsulation.py)
90 | 5. **進階技巧**
91 | - 裝飾器:[Decorator definition | wraps](ultimatepython/advanced/decorator.py) ( 🤯 )
92 | - 文件處理: [File Handling](ultimatepython/advanced/file_handling.py) ( 🤯 )
93 | - 資源管理器:[Context managers](ultimatepython/advanced/context_manager.py) ( 🤯 )
94 | - 方法解析順序:[mro](ultimatepython/advanced/mro.py) ( 🤯 )
95 | - Mixin:[Mixin定義](ultimatepython/advanced/mixin.py) ( 🤯 )
96 | - 元類:[Metaclass定義](ultimatepython/advanced/meta_class.py) ( 🤯 )
97 | - 執行緒:[ThreadPoolExecutor](ultimatepython/advanced/thread.py) ( 🤯 )
98 | - 異步:[async | await](ultimatepython/advanced/async.py) ( 🤯 )
99 | - 弱引用:[weakref](ultimatepython/advanced/weak_ref.py) ( 🤯 )
100 | - 基準:[cProfile | pstats](ultimatepython/advanced/benchmark.py) ( 🤯 )
101 | - 模擬:[MagicMock | PropertyMock | patch](ultimatepython/advanced/mocking.py) ( 🤯 )
102 | - 正規表示式:[search | findall | match | fullmatch](ultimatepython/advanced/regex.py) ( 🤯 )
103 | - 數據格式:[json | xml | csv](ultimatepython/advanced/data_format.py) ( 🤯 )
104 | - 日期時間: [datetime | timezone](ultimatepython/advanced/date_time.py) ( 🤯 )
105 |
106 | ## 額外資源
107 |
108 | 👔 = 面試資源,
109 | 🧪 = 代碼範例,
110 | 🧠 = 項目構想
111 |
112 | ### GitHub儲存庫
113 |
114 | 通過閱讀其他備受尊重的資源來繼續學習。
115 |
116 | - [TheAlgorithms/Python](https://github.com/TheAlgorithms/Python) ( 👔, 🧪 )
117 | - [faif/python-patterns](https://github.com/faif/python-patterns) ( 👔, 🧪 )
118 | - [geekcomputers/Python](https://github.com/geekcomputers/Python) ( 🧪 )
119 | - [trekhleb/homemade-machine-learning](https://github.com/trekhleb/homemade-machine-learning) ( 🧪 )
120 | - [karan/Projects](https://github.com/karan/Projects) ( 🧠 )
121 | - [MunGell/awesome-for-beginners](https://github.com/MunGell/awesome-for-beginners) ( 🧠 )
122 | - [vinta/awesome-python](https://github.com/vinta/awesome-python)
123 | - [academic/awesome-datascience](https://github.com/academic/awesome-datascience)
124 | - [josephmisiti/awesome-machine-learning](https://github.com/josephmisiti/awesome-machine-learning)
125 | - [ZuzooVn/machine-learning-for-software-engineers](https://github.com/ZuzooVn/machine-learning-for-software-engineers)
126 | - [30-seconds/30-seconds-of-python](https://github.com/30-seconds/30-seconds-of-python) ( 🧪 )
127 | - [ml-tooling/best-of-python](https://github.com/ml-tooling/best-of-python)
128 | - [practical-tutorials/project-based-learning](https://github.com/practical-tutorials/project-based-learning#python)
129 | - [freeCodeCamp/freeCodeCamp](https://github.com/freeCodeCamp/freeCodeCamp) ( 👔 )
130 |
131 | ### 互動練習
132 |
133 | 繼續練習才能使您的編碼技能不會生疏。
134 |
135 | - [DevProjects](https://www.codementor.io/projects/python)
136 | - [codechef.com](https://www.codechef.com/) ( 👔 )
137 | - [codeforces.com](https://codeforces.com/)
138 | - [coderbyte.com](https://www.coderbyte.com/) ( 👔 )
139 | - [codewars.com](https://www.codewars.com/)
140 | - [exercism.io](https://exercism.io/)
141 | - [geeksforgeeks.org](https://www.geeksforgeeks.org/) ( 👔 )
142 | - [hackerearth.com](https://www.hackerearth.com/)
143 | - [hackerrank.com](https://www.hackerrank.com/) ( 👔 )
144 | - [kaggle.com](https://www.kaggle.com/) ( 🧠 )
145 | - [leetcode.com](https://leetcode.com/) ( 👔 )
146 | - [projecteuler.net](https://projecteuler.net/)
147 | - [replit.com](https://replit.com/)
148 | - [w3schools.com](https://www.w3schools.com/python/) ( 🧪 )
149 |
--------------------------------------------------------------------------------
/codecov.yml:
--------------------------------------------------------------------------------
1 | # https://docs.codecov.com/docs/common-recipe-list
2 | # https://docs.codecov.com/docs/commit-status
3 | coverage:
4 | status:
5 | patch:
6 | default:
7 | target: 100%
8 |
--------------------------------------------------------------------------------
/images/ultimatepython.webp:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangsam/ultimate-python/26887e626b9509aa56f99da604399ed800405aaa/images/ultimatepython.webp
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [tool.ruff]
2 | line-length = 160
3 |
4 | [tool.isort]
5 | multi_line_output = 3
6 | include_trailing_comma = true
7 | force_grid_wrap = 0
8 | use_parentheses = true
9 | ensure_newline_before_comments = true
10 | line_length = 160
11 |
12 | [tool.coverage.run]
13 | branch = true
14 |
15 | [tool.coverage.report]
16 | exclude_lines = [
17 | "skip: (if|else)",
18 | "def __repr__",
19 | "raise NotImplementedError",
20 | "if __name__ == .__main__.:",
21 | "any\\("
22 | ]
23 | fail_under = 80
24 | omit = [
25 | "venv/**",
26 | "runner.py",
27 | "**/__init__.py"
28 | ]
29 |
--------------------------------------------------------------------------------
/requirements.txt:
--------------------------------------------------------------------------------
1 | coverage==7.8.2
2 | isort==6.0.1
3 | ruff==0.11.11
4 |
--------------------------------------------------------------------------------
/runner.py:
--------------------------------------------------------------------------------
1 | from importlib import import_module
2 | from inspect import isfunction, signature
3 | from pkgutil import walk_packages
4 |
5 | from ultimatepython import __name__ as root_name
6 | from ultimatepython import __path__ as root_path
7 |
8 | # Module-level constants
9 | _STYLE_SUCCESS = "\033[92m"
10 | _STYLE_BOLD = "\033[1m"
11 | _STYLE_END = "\033[0m"
12 | _RUNNER_PROGRESS = "->"
13 | _RUNNER_MAIN = "main"
14 |
15 |
16 | def success_text(text):
17 | """Get success text."""
18 | return f"{_STYLE_SUCCESS}{bold_text(text)}{_STYLE_END}"
19 |
20 |
21 | def bold_text(text):
22 | """Get bold text."""
23 | return f"{_STYLE_BOLD}{text}{_STYLE_END}"
24 |
25 |
26 | def main():
27 | print(bold_text(f"Start {root_name} runner"))
28 |
29 | for item in walk_packages(root_path, f"{root_name}."):
30 | mod = import_module(item.name)
31 |
32 | # Skip modules without a main object
33 | if not hasattr(mod, _RUNNER_MAIN):
34 | continue
35 |
36 | # By this point, there is a main object in the module
37 | mod_main = getattr(mod, _RUNNER_MAIN)
38 |
39 | # The main object is a function
40 | assert isfunction(mod_main)
41 |
42 | # The main function has zero parameters
43 | assert len(signature(mod_main).parameters) == 0
44 |
45 | # The main function should not throw any errors
46 | print(f"{_RUNNER_PROGRESS} Run {mod.__name__}:{_RUNNER_MAIN}", end="")
47 | mod_main()
48 | print(" [PASS]")
49 |
50 | print(success_text(f"Finish {root_name} runner"))
51 |
52 |
53 | if __name__ == "__main__":
54 | main()
55 |
--------------------------------------------------------------------------------
/ultimatepython/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangsam/ultimate-python/26887e626b9509aa56f99da604399ed800405aaa/ultimatepython/__init__.py
--------------------------------------------------------------------------------
/ultimatepython/advanced/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/huangsam/ultimate-python/26887e626b9509aa56f99da604399ed800405aaa/ultimatepython/advanced/__init__.py
--------------------------------------------------------------------------------
/ultimatepython/advanced/async.py:
--------------------------------------------------------------------------------
1 | """
2 | Concurrent programming with an event loop is a relatively new concept in
3 | Python 3.x. This module aims to highlight how it could be used in the
4 | context of a scheduler which runs a fire-and-forget operation for starting
5 | jobs. In the real world, it takes time for a scheduler to start a job (i.e.
6 | hit an API endpoint, ask the operating system for resources) so we assume
7 | that starting a job has some intrinsic delay.
8 | """
9 | import asyncio
10 | from dataclasses import dataclass
11 | from datetime import datetime
12 | from uuid import uuid4
13 |
14 | # Module-level constants
15 | _DELAY_SMALL = 0.001
16 | _DELAY_LARGE = 3600
17 |
18 |
19 | @dataclass
20 | class JobRecord:
21 | """Job record with useful metadata."""
22 |
23 | guid: str
24 | queued_at: datetime
25 | started_at: datetime
26 |
27 |
28 | def _is_valid_record(record):
29 | """Check whether job record is valid or not."""
30 | return record.queued_at < record.started_at
31 |
32 |
33 | def _current_time():
34 | """Return current time that is timezone-naive."""
35 | return datetime.now()
36 |
37 |
38 | async def start_job(job_id, delay):
39 | """Start job ID after a certain amount of delay."""
40 | queue_time = _current_time()
41 | await asyncio.sleep(delay)
42 | start_time = _current_time()
43 | return JobRecord(job_id, queue_time, start_time)
44 |
45 |
46 | async def schedule_jobs():
47 | """Schedule jobs concurrently."""
48 | # Start a job which also represents a coroutine
49 | single_job = start_job(uuid4().hex, _DELAY_SMALL)
50 | assert asyncio.iscoroutine(single_job)
51 |
52 | # Grab a job record from the coroutine
53 | single_record = await single_job
54 | assert _is_valid_record(single_record)
55 |
56 | # Task is a wrapped coroutine which also represents a future
57 | single_task = asyncio.create_task(start_job(uuid4().hex, _DELAY_LARGE))
58 | assert asyncio.isfuture(single_task)
59 |
60 | # Futures are different from other coroutines since they can be cancelled
61 | single_task.cancel()
62 | task_failed = False
63 | try:
64 | await single_task
65 | except asyncio.exceptions.CancelledError:
66 | assert single_task.cancelled()
67 | task_failed = True
68 | assert task_failed is True
69 |
70 | # Gather coroutines for batch start
71 | batch_jobs = [start_job(uuid4().hex, _DELAY_SMALL) for _ in range(10)]
72 | batch_records = await asyncio.gather(*batch_jobs)
73 |
74 | # We get the same amount of records as we have coroutines
75 | assert len(batch_records) == len(batch_jobs)
76 | assert all(_is_valid_record(record) for record in batch_records)
77 |
78 |
79 | def main():
80 | asyncio.run(schedule_jobs())
81 |
82 |
83 | if __name__ == "__main__":
84 | main()
85 |
--------------------------------------------------------------------------------
/ultimatepython/advanced/benchmark.py:
--------------------------------------------------------------------------------
1 | """
2 | As programs increase in size, they have the risk of getting slow as new
3 | features are added and extra layers of complexity to the main features.
4 | Benchmarking is an approach that helps developers use profiling metrics
5 | and their code intuition to optimize programs further. This module uses
6 | cProfile to compare the performance of two functions with each other.
7 | """
8 | import cProfile
9 | import io
10 | import pstats
11 | import time
12 |
13 | # Module-level constants
14 | _SLEEP_DURATION = 0.001
15 |
16 |
17 | def finish_slower():
18 | """Finish slower by sleeping more."""
19 | for _ in range(20):
20 | time.sleep(_SLEEP_DURATION)
21 |
22 |
23 | def finish_faster():
24 | """Finish faster by sleeping less."""
25 | for _ in range(10):
26 | time.sleep(_SLEEP_DURATION)
27 |
28 |
29 | def main():
30 | # Create a profile instance
31 | profile = cProfile.Profile()
32 |
33 | profile.enable()
34 |
35 | for _ in range(2):
36 | finish_slower()
37 | finish_faster()
38 |
39 | profile.disable()
40 |
41 | # Sort statistics by cumulative time spent for each function call.
42 | # There are other ways to sort the stats by, but this is the most
43 | # common way of doing so. For more info, please consult Python docs:
44 | # https://docs.python.org/3/library/profile.html
45 | buffer = io.StringIO()
46 | ps = pstats.Stats(profile, stream=buffer).sort_stats("cumulative")
47 |
48 | # Notice how many times each function was called. In this case, the main
49 | # bottleneck for `finish_slower` and `finish_faster` is `time.sleep`
50 | # which occurred 60 times. By reading the code and the statistics, we
51 | # can infer that 40 occurrences came from `finish_slower` and 20 came
52 | # from `finish_faster`. It is clear why the latter function runs faster
53 | # in this case, but identifying insights like this are not simple in
54 | # large projects. Consider profiling in isolation when analyzing complex
55 | # classes and functions
56 | ps.print_stats()
57 | time_sleep_called = any("60" in line and "time.sleep" in line
58 | for line in buffer.getvalue().split("\n"))
59 | assert time_sleep_called is True
60 |
61 |
62 | if __name__ == "__main__":
63 | main()
64 |
--------------------------------------------------------------------------------
/ultimatepython/advanced/context_manager.py:
--------------------------------------------------------------------------------
1 | """
2 | Context managers are used to open and close resources as Python enters
3 | and exits a code block respectively. Some examples of the resources it
4 | can manage are files, database connections and sockets. In this module,
5 | we simulate how a context manager can handle open and close operations of
6 | a file-like object called StringIO.
7 | """
8 | from contextlib import contextmanager
9 | from io import StringIO
10 |
11 | # Simple directory with file contents
12 | _FILESYSTEM = {
13 | "a.txt": "Hello World",
14 | "b.xml": "
Invalid entry for {request.url}
" 72 | 73 | @abstractmethod 74 | def render_template(self, template_name): 75 | """Render contents of specified template name.""" 76 | raise NotImplementedError 77 | 78 | 79 | class AuthHandlerMixin(RequestHandler): 80 | """Abstract auth mixin for RequestHandler. 81 | 82 | This is another mixin class where authentication helper methods are 83 | defined in this abstract class and must be implemented in concrete 84 | classes. Notice that the `handle` method is implemented and returns 85 | the output of the parent's `handle` method. This means that we can 86 | continue to chain mixin effects as long as this mixin is to the left 87 | of another mixin in a concrete class MRO. 88 | """ 89 | 90 | def handle(self, request): 91 | if not self.is_valid_user(request.user): 92 | return self.handle_invalid_user(request) 93 | return super().handle(request) 94 | 95 | @abstractmethod 96 | def is_valid_user(self, request_user): 97 | """Check if user is valid.""" 98 | raise NotImplementedError 99 | 100 | @staticmethod 101 | def handle_invalid_user(request): 102 | """Handle request for invalid user.""" 103 | return f"Access denied for {request.url}
" 104 | 105 | 106 | class TemplateFolderHandler(TemplateHandlerMixin): 107 | """Concrete template handler. 108 | 109 | This concrete class implements the abstract methods of its parent 110 | mixin. By extension, it has implemented everything that is needed 111 | for the `handle` method. 112 | """ 113 | 114 | def __init__(self, template_dir): 115 | self.template_dir = template_dir 116 | 117 | def get_template_name(self, request_url): 118 | return request_url[1:] 119 | 120 | def is_valid_template(self, template_name): 121 | return (super().is_valid_template(template_name) 122 | and template_name in self.template_dir) 123 | 124 | def render_template(self, template_name): 125 | return self.template_dir[template_name] 126 | 127 | 128 | class AdminTemplateHandler(AuthHandlerMixin, TemplateFolderHandler): 129 | """Concrete auth and template handler. 130 | 131 | This concrete class gets the benefits of the previous concrete 132 | class but also gets authentication for free just by implementing 133 | the abstract method of the authentication mixin. 134 | """ 135 | 136 | def __init__(self, admin_users, template_dir): 137 | super().__init__(template_dir) 138 | self.admin_users = admin_users 139 | 140 | def is_valid_user(self, request_user): 141 | return request_user in self.admin_users 142 | 143 | 144 | def main(): 145 | # Handle requests with simple template handler 146 | simple_dir = {"welcome.template": "Hello world
", 147 | "about.template": "About me
"} 148 | simple_handler = TemplateFolderHandler(simple_dir) 149 | welcome_from_nobody = Request("/welcome.template", "nobody") 150 | about_from_nobody = Request("/about.template", "nobody") 151 | foo_from_nobody = Request("/foo.bar", "nobody") 152 | assert simple_handler.handle(welcome_from_nobody) == "Hello world
" 153 | assert simple_handler.handle(about_from_nobody) == "About me
" 154 | assert simple_handler.handle(foo_from_nobody) == "Invalid entry for /foo.bar
" 155 | 156 | # Handle requests with admin template handler 157 | admin_users = {"john", "jane"} 158 | admin_dir = {"fqdn.template": "server.example.com
", 159 | "salary.template": "123456789.00
"} 160 | admin_handler = AdminTemplateHandler(admin_users, admin_dir) 161 | fqdn_from_john = Request("/fqdn.template", "john") 162 | salary_from_jane = Request("/salary.template", "jane") 163 | salary_from_nobody = Request("/salary.template", "nobody") 164 | foo_from_john = Request("/foo.bar", "john") 165 | assert admin_handler.handle(fqdn_from_john) == "server.example.com
" 166 | assert admin_handler.handle(salary_from_jane) == "123456789.00
" 167 | assert admin_handler.handle(salary_from_nobody) == "Access denied for /salary.template
" 168 | assert admin_handler.handle(foo_from_john) == "Invalid entry for /foo.bar
" 169 | 170 | 171 | if __name__ == "__main__": 172 | main() 173 | -------------------------------------------------------------------------------- /ultimatepython/advanced/mocking.py: -------------------------------------------------------------------------------- 1 | """ 2 | Mocking objects is a common strategy that developers use to test code that 3 | depends on an external system or external resources for it to work 4 | properly. This module shows how to use mocking to modify an application 5 | server so that it is easier to test. 6 | """ 7 | from collections import Counter 8 | from unittest.mock import MagicMock, PropertyMock, patch 9 | 10 | # Module-level constants 11 | _COUNTER = Counter(pid=1) 12 | _START_SUCCESS = "success" 13 | _START_FAILURE = "failure" 14 | _PROTOCOL_HTTP = "http" 15 | _PROTOCOL_HTTPS = "https" 16 | _FAKE_BASE_URL = f"{_PROTOCOL_HTTPS}://www.google.com:443" 17 | _FAKE_PID = 127 18 | 19 | 20 | class AppServer: 21 | """Application server. 22 | 23 | Normally we don't mock an application server because it is the runtime 24 | environment (AKA central nervous system) for business logic, database 25 | endpoints, network sockets and more. However, this server definition 26 | is lightweight, so it's okay to mock this. 27 | """ 28 | 29 | def __init__(self, host, port, proto): 30 | self._host = host 31 | self._port = port 32 | self._proto = proto 33 | self._pid = -1 34 | 35 | @property 36 | def endpoint(self): 37 | """Get application server endpoint URL.""" 38 | return f"{self._proto}://{self._host}:{self._port}" 39 | 40 | @property 41 | def pid(self): 42 | """Get application server process ID.""" 43 | return self._pid 44 | 45 | @property 46 | def started(self): 47 | """Check if application server is started.""" 48 | return self.pid > 0 49 | 50 | def start(self): 51 | """Start application server.""" 52 | if self.started: 53 | return _START_FAILURE 54 | self._pid = _COUNTER["pid"] 55 | _COUNTER["pid"] += 1 56 | return _START_SUCCESS 57 | 58 | 59 | class FakeServer(AppServer): 60 | """Subclass parent and fake some routines.""" 61 | 62 | @property 63 | def endpoint(self): 64 | """Mock output of endpoint URL.""" 65 | return _FAKE_BASE_URL 66 | 67 | @property 68 | def pid(self): 69 | """Mock output of process ID.""" 70 | return _FAKE_PID 71 | 72 | 73 | def main(): 74 | # This is the original class instance and it works as expected 75 | app_server = AppServer("localhost", 8000, _PROTOCOL_HTTP) 76 | assert app_server.endpoint == f"{_PROTOCOL_HTTP}://localhost:8000" 77 | assert app_server.start() == _START_SUCCESS 78 | assert app_server.started is True 79 | assert app_server.start() == _START_FAILURE 80 | 81 | # But sometimes we cannot test the finer details of a class because 82 | # its methods depend on the availability of external resources. This 83 | # is where mocking comes to the rescue. There are a couple approaches 84 | # that developers use when it comes to mocking 85 | 86 | # Approach 1: Use a `MagicMock` in place of a real class instance 87 | mock_server = MagicMock() 88 | assert isinstance(mock_server, MagicMock) 89 | assert isinstance(mock_server.start_server(), MagicMock) 90 | mock_server.start_server.assert_called() 91 | mock_server.endpoint.assert_not_called() 92 | 93 | # Approach 2: Patch a method in the original class 94 | with patch.object(AppServer, "endpoint", PropertyMock(return_value=_FAKE_BASE_URL)): 95 | patch_server = AppServer("localhost", 8080, _PROTOCOL_HTTP) 96 | assert isinstance(patch_server, AppServer) 97 | assert patch_server.endpoint == _FAKE_BASE_URL 98 | assert patch_server.started is False 99 | assert patch_server.start() == _START_SUCCESS 100 | 101 | # Approach 3: Create a new class that inherits the original class 102 | fake_server = FakeServer("localhost", 8080, _PROTOCOL_HTTP) 103 | assert isinstance(fake_server, AppServer) 104 | assert fake_server.endpoint == _FAKE_BASE_URL 105 | assert fake_server.started is True 106 | assert patch_server.start() == _START_FAILURE 107 | 108 | 109 | if __name__ == "__main__": 110 | main() 111 | -------------------------------------------------------------------------------- /ultimatepython/advanced/mro.py: -------------------------------------------------------------------------------- 1 | """ 2 | MRO stands for method resolution order, and it's used by class definitions 3 | to determine which method will be run by a class instance. This module 4 | shows how the MRO is useful for the classic diamond problem where classes 5 | B and C depend on class A, and class D depends on classes B and C. 6 | """ 7 | 8 | 9 | class BasePlayer: 10 | """Base player.""" 11 | 12 | def ping(self): 13 | return "ping" 14 | 15 | def pong(self): 16 | return "pong" 17 | 18 | 19 | class PongPlayer(BasePlayer): 20 | """Pong player.""" 21 | 22 | def pong(self): 23 | return "PONG" 24 | 25 | 26 | class NeutralPlayer(BasePlayer): 27 | """Neutral player.""" 28 | 29 | 30 | class ConfusedPlayer(PongPlayer, NeutralPlayer): 31 | """Confused player. 32 | 33 | This is what we call the diamond problem, where `BasePlayer` child classes 34 | are the same as `ConfusedPlayer` parent classes. Python has the MRO to 35 | determine which `ping` and `pong` methods are called via the `super()` 36 | call followed by the respective method. 37 | 38 | The `super()` call is usually used without any parameters, which 39 | means that we start the MRO process from the current class upwards. 40 | 41 | For more on the subject, please consult this link: 42 | 43 | https://www.python.org/download/releases/2.3/mro/ 44 | """ 45 | 46 | def ping(self): 47 | """Override `ping` method.""" 48 | return "pINg" 49 | 50 | def ping_pong(self): 51 | """Run `ping` and `pong` in different ways.""" 52 | return [ 53 | self.ping(), 54 | super().ping(), 55 | self.pong(), 56 | super().pong() 57 | ] 58 | 59 | 60 | class IndecisivePlayer(NeutralPlayer, PongPlayer): 61 | """Indecisive player. 62 | 63 | Notice that this class was created successfully without any conflicts 64 | even though the MRO of `ConfusedPlayer` is different. 65 | 66 | Notice that one of the `super()` calls uses additional parameters to 67 | start the MRO process from another class. This is generally discouraged 68 | as this bypasses the default method resolution process. 69 | """ 70 | 71 | def pong(self): 72 | """Override `pong` method.""" 73 | return "pONg" 74 | 75 | def ping_pong(self): 76 | """Run `ping` and `pong` in different ways.""" 77 | return [ 78 | self.ping(), 79 | super().ping(), 80 | self.pong(), 81 | super(PongPlayer, self).pong() # bypass MRO to `BasePlayer` 82 | ] 83 | 84 | 85 | def main(): 86 | # `ConfusedPlayer` methods are resolved from child to parent like this 87 | assert ConfusedPlayer.mro() == [ 88 | ConfusedPlayer, PongPlayer, NeutralPlayer, BasePlayer, object] 89 | 90 | # `IndecisivePlayer` methods are resolved from child to parent like this 91 | assert IndecisivePlayer.mro() == [ 92 | IndecisivePlayer, NeutralPlayer, PongPlayer, BasePlayer, object] 93 | 94 | # Show `ConfusedPlayer` method resolution in action 95 | assert ConfusedPlayer().ping_pong() == ["pINg", "ping", "PONG", "PONG"] 96 | 97 | # Show `IndecisivePlayer` method resolution in action 98 | assert IndecisivePlayer().ping_pong() == ["ping", "ping", "pONg", "pong"] 99 | 100 | class_creation_failed = False 101 | try: 102 | # Creating a new class `ConfusedPlayer` and `IndecisivePlayer` 103 | # results in a `TypeError` because both classes do not have 104 | # matching MRO outputs. This means that they cannot be reconciled 105 | # as one class. Hence, `MissingPlayer` will not be created 106 | type("MissingPlayer", (ConfusedPlayer, IndecisivePlayer), {}) 107 | except TypeError: 108 | class_creation_failed = True 109 | assert class_creation_failed is True 110 | 111 | 112 | if __name__ == "__main__": 113 | main() 114 | -------------------------------------------------------------------------------- /ultimatepython/advanced/regex.py: -------------------------------------------------------------------------------- 1 | """ 2 | Using regular expressions is a robust way to search for text. Implementing 3 | them is difficult but Python provides a package for us to use them easily. 4 | This module shows a few examples of how to use the `re` package to search 5 | predefined text snippets stored in module-level constants. 6 | """ 7 | import re 8 | 9 | # Module-level constants 10 | _TEXT_HELLO = "World Hello Hello" 11 | _TEXT_NAMES = "John, Jane" 12 | _TEXT_ABC123 = "abc123" 13 | _TEXT_BYE = "Bye for now" 14 | _TEXT_EMAILS = "My work email is kayode@dodo.ng while nerdthejohn@yahoo.com is personal" 15 | 16 | 17 | def main(): 18 | # Running `search` with "Hello" has a match for first Hello 19 | assert re.search(r"Hello", _TEXT_HELLO).start() == 6 20 | 21 | # Running `search` with "Hello$" has a match for last Hello 22 | assert re.search(r"Hello$", _TEXT_HELLO).start() == 12 23 | 24 | # Running `search` with "(Hello) (Hello)" has matches for Hello 25 | assert re.search(r"(Hello) (Hello)", _TEXT_HELLO).groups() == ("Hello", "Hello") 26 | 27 | # Running `findall` with "Hi \w+" has a list of strings 28 | assert re.findall(r"\w+", _TEXT_NAMES) == ["John", "Jane"] 29 | 30 | # Running `findall` with "[a-z]+@[a-z]+\.[a-z]+" has a list of email strings 31 | assert re.findall(r"[a-z]+@[a-z]+\.[a-z]+", _TEXT_EMAILS) == ["kayode@dodo.ng", "nerdthejohn@yahoo.com"] 32 | 33 | # Running `match` with "[123]+" has nothing 34 | assert re.match(r"[123]+", _TEXT_ABC123) is None 35 | 36 | # Running `match` with "[abc]+" has a match for abc 37 | assert re.match(r"[abc]+", _TEXT_ABC123).group(0) == "abc" 38 | 39 | # Running `fullmatch` with "[\w]+" has nothing 40 | assert re.fullmatch(r"[\w]+", _TEXT_BYE) is None 41 | 42 | # Running `fullmatch` with "[\w ]+" has a full match 43 | assert re.fullmatch(r"[\w ]+", _TEXT_BYE).group(0) == _TEXT_BYE 44 | 45 | # To learn more about regular expressions: 46 | # https://en.wikipedia.org/wiki/Regular_expression 47 | # https://github.com/ziishaned/learn-regex 48 | 49 | # To play around with regular expressions in the browser: 50 | # https://regex101.com 51 | 52 | 53 | if __name__ == "__main__": 54 | main() 55 | -------------------------------------------------------------------------------- /ultimatepython/advanced/thread.py: -------------------------------------------------------------------------------- 1 | """ 2 | Threaded programming is used by developers to improve the performance of 3 | an application. This module shows how a multiplication operation with 4 | some delay can be parallelized using `ThreadPoolExecutor`. 5 | 6 | A good grasp of threads is recommended, but not necessary, before 7 | reading the code below. 8 | 9 | Here are some resources to learn more about threads: 10 | 11 | https://realpython.com/intro-to-python-threading/ 12 | https://docs.python.org/3/library/threading.html 13 | 14 | Python threads are not suitable for CPU-heavy tasks in the CPython 15 | interpreter due to the GIL. To address this, we typically resort to 16 | forking processes or running C externally. 17 | 18 | Here are some resources to learn more about the GIL: 19 | 20 | https://realpython.com/python-gil/ 21 | https://wiki.python.org/moin/GlobalInterpreterLock 22 | """ 23 | import time 24 | from concurrent.futures import ThreadPoolExecutor, as_completed 25 | from datetime import datetime 26 | 27 | # Module-level constants 28 | _MULTIPLY_DELAY = 0.01 # delay is long enough for threads to be faster 29 | 30 | 31 | def multiply_by_two(item): 32 | """This multiplication has a small delay.""" 33 | time.sleep(_MULTIPLY_DELAY) 34 | return item * 2 35 | 36 | 37 | def run_thread_workers(work, data): 38 | """Run thread workers that invoke work on each data element. 39 | 40 | The inspiration for this function comes directly from an example 41 | in the Python 3.x documentation: 42 | 43 | https://docs.python.org/3/library/concurrent.futures.html 44 | """ 45 | results = set() 46 | 47 | # We can use a with statement to ensure workers are cleaned up promptly 48 | with ThreadPoolExecutor() as executor: 49 | # Note that results are returned out of order 50 | work_queue = (executor.submit(work, item) for item in data) 51 | for future in as_completed(work_queue): 52 | results.add(future.result()) 53 | 54 | return results 55 | 56 | 57 | def main(): 58 | original_data = {num for num in range(5)} 59 | expected_data = {(item * 2) for item in original_data} 60 | 61 | # Let's get the data using the simple approach 62 | simple_start = datetime.now() 63 | simple_data = {multiply_by_two(item) for item in original_data} 64 | simple_duration = datetime.now() - simple_start 65 | 66 | # The simple approach has the expected data 67 | assert simple_data == expected_data 68 | 69 | # Let's get the data using the threaded approach 70 | thread_start = datetime.now() 71 | thread_data = run_thread_workers(multiply_by_two, original_data) 72 | thread_duration = datetime.now() - thread_start 73 | 74 | # The threaded approach has the expected data 75 | assert thread_data == expected_data 76 | 77 | # The threaded approach is faster than the simple approach in this case 78 | # because a blocking I/O call like time.sleep forces the current thread 79 | # to yield its control over to a waiting thread to start running. That 80 | # means the threaded approach can run blocking operations in parallel. 81 | # The cost of creating threads is somewhat cheap which means we often 82 | # create more than one thread to speed up I/O-heavy workloads 83 | assert thread_duration < simple_duration 84 | 85 | 86 | if __name__ == "__main__": 87 | main() 88 | -------------------------------------------------------------------------------- /ultimatepython/advanced/weak_ref.py: -------------------------------------------------------------------------------- 1 | """ 2 | Weak references are a way to help the Python interpreter remove unused data 3 | more easily. This module shows how it can be used to keep a server registry 4 | up-to-date as it explicitly sets up and implicitly tears down servers as 5 | the program enters and leaves a function scope. 6 | """ 7 | import weakref 8 | from uuid import uuid4 9 | 10 | # Module-level constants 11 | _CLOUD_PROVIDER = "aws" 12 | _CLOUD_APPS = ["yelp", "pinterest", "uber", "twitter"] 13 | _CLOUD_APP_COMPONENTS = ("db", "web", "cache") 14 | 15 | 16 | class Server: 17 | """General server.""" 18 | 19 | @classmethod 20 | def create(cls, role, provider=_CLOUD_PROVIDER): 21 | """Create server with autogenerated SSID.""" 22 | return cls(uuid4().hex, role, provider) 23 | 24 | def __init__(self, ssid, role, provider): 25 | self.ssid = ssid 26 | self.role = role 27 | self.provider = provider 28 | 29 | 30 | class ServerRegistry: 31 | """Server registry with weak references.""" 32 | 33 | def __init__(self): 34 | self._servers = weakref.WeakSet() 35 | 36 | @property 37 | def servers(self): 38 | """Get set of added servers.""" 39 | return {s for s in self._servers} 40 | 41 | @property 42 | def server_count(self): 43 | """Get count of added servers.""" 44 | return len(self.servers) 45 | 46 | def add(self, server): 47 | """Add server to registry.""" 48 | self._servers.add(server) 49 | 50 | 51 | def setup_and_teardown_servers(registry): 52 | """Explicitly setup and implicitly teardown servers.""" 53 | app_servers = {} 54 | 55 | # Let's create all the servers and store them properly 56 | for app in _CLOUD_APPS: 57 | app_servers[app] = set() 58 | for component in _CLOUD_APP_COMPONENTS: 59 | server = Server.create(f"{app}_{component}") 60 | registry.add(server) 61 | app_servers[app].add(server) 62 | 63 | # All of these counts are equivalent. This is no surprise since our 64 | # for loop unconditionally creates a server for every permutation of 65 | # apps and components. The loop also adds each server to the registry 66 | # and dictionary unconditionally 67 | assert ( 68 | registry.server_count 69 | == len(_CLOUD_APPS) * len(_CLOUD_APP_COMPONENTS) 70 | == len([(app, server) 71 | for app, servers in app_servers.items() 72 | for server in servers]) 73 | ) 74 | 75 | # What's fascinating is that servers go away when we leave the 76 | # scope of this function. In this function, each server is created and 77 | # strongly referenced by the `app_servers` variable. When we leave this 78 | # function, the `app_servers` variable no longer exists which brings 79 | # the reference count for each server from 1 to 0. A reference count of 80 | # 0 for each server triggers the garbage collector to run the cleanup 81 | # process for all the servers in this function scope 82 | 83 | 84 | def main(): 85 | # Initialize a server registry 86 | registry = ServerRegistry() 87 | 88 | # Setup and teardown servers with the registry 89 | setup_and_teardown_servers(registry) 90 | 91 | # Notice that our registry does not remember the servers because 92 | # it uses weak references. Because there are no strong references 93 | # to the created servers in `setup_and_teardown_servers`, the 94 | # garbage collector cleans up the servers. This behavior is usually 95 | # desired if we want to keep our software memory-efficient 96 | assert registry.servers == set() 97 | assert registry.server_count == 0 98 | 99 | 100 | if __name__ == "__main__": 101 | main() 102 | -------------------------------------------------------------------------------- /ultimatepython/classes/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/huangsam/ultimate-python/26887e626b9509aa56f99da604399ed800405aaa/ultimatepython/classes/__init__.py -------------------------------------------------------------------------------- /ultimatepython/classes/abstract_class.py: -------------------------------------------------------------------------------- 1 | """ 2 | Abstract class is an extension of a basic class. Like a basic class, an 3 | abstract class has methods and state. Unlike a basic class, it inherits 4 | the `ABC` class and has at least one `abstractmethod`. That means we 5 | cannot create an instance directly from its constructor. In this module, 6 | we will create an abstract class and two concrete classes. 7 | 8 | For more about abstract classes, click the link below: 9 | 10 | https://www.python.org/dev/peps/pep-3119/ 11 | """ 12 | from abc import ABC, abstractmethod 13 | 14 | 15 | class Employee(ABC): 16 | """Abstract definition of an employee. 17 | 18 | Any employee can work and relax. The way that one type of employee 19 | can work and relax is different from another type of employee. 20 | """ 21 | 22 | def __init__(self, name, title): 23 | self.name = name 24 | self.title = title 25 | 26 | def __str__(self): 27 | return self.name 28 | 29 | @abstractmethod 30 | def do_work(self): 31 | """Do something for work.""" 32 | raise NotImplementedError 33 | 34 | @abstractmethod 35 | def do_relax(self): 36 | """Do something to relax.""" 37 | raise NotImplementedError 38 | 39 | 40 | class Engineer(Employee): 41 | """Concrete definition of an engineer. 42 | 43 | The Engineer class is concrete because it implements every 44 | `abstractmethod` that was not implemented above. 45 | 46 | Notice that we leverage the parent's constructor when creating 47 | this object. We also define `do_refactor` for an engineer, which 48 | is something that a manager prefers not to do. 49 | """ 50 | 51 | def __init__(self, name, title, skill): 52 | super().__init__(name, title) 53 | self.skill = skill 54 | 55 | def do_work(self): 56 | return f"{self} is coding in {self.skill}" 57 | 58 | def do_relax(self): 59 | return f"{self} is watching YouTube" 60 | 61 | def do_refactor(self): 62 | """Do the hard work of refactoring code, unlike managers.""" 63 | return f"{self} is refactoring code" 64 | 65 | 66 | class Manager(Employee): 67 | """Concrete definition of a manager. 68 | 69 | The Manager class is concrete for the same reasons as the Engineer 70 | class is concrete. Notice that a manager has direct reports and 71 | has the responsibility of hiring people on the team, unlike an 72 | engineer. 73 | """ 74 | 75 | def __init__(self, name, title, direct_reports): 76 | super().__init__(name, title) 77 | self.direct_reports = direct_reports 78 | 79 | def do_work(self): 80 | return f"{self} is meeting up with {len(self.direct_reports)} reports" 81 | 82 | def do_relax(self): 83 | return f"{self} is taking a trip to the Bahamas" 84 | 85 | def do_hire(self): 86 | """Do the hard work of hiring employees, unlike engineers.""" 87 | return f"{self} is hiring employees" 88 | 89 | 90 | def main(): 91 | # Declare two engineers 92 | engineer_john = Engineer("John Doe", "Software Engineer", "Android") 93 | engineer_jane = Engineer("Jane Doe", "Software Engineer", "iOS") 94 | engineers = [engineer_john, engineer_jane] 95 | 96 | # These engineers are employees but not managers 97 | assert all(isinstance(engineer, Employee) for engineer in engineers) 98 | assert all(not isinstance(engineer, Manager) for engineer in engineers) 99 | 100 | # Engineers can work, relax and refactor 101 | assert engineer_john.do_work() == "John Doe is coding in Android" 102 | assert engineer_john.do_relax() == "John Doe is watching YouTube" 103 | assert engineer_john.do_refactor() == "John Doe is refactoring code" 104 | 105 | # Declare manager with engineers as direct reports 106 | manager_max = Manager("Max Doe", "Engineering Manager", engineers) 107 | 108 | # Managers are employees but not engineers 109 | assert isinstance(manager_max, Employee) 110 | assert not isinstance(manager_max, Engineer) 111 | 112 | # Managers can work, relax and hire 113 | assert manager_max.do_work() == "Max Doe is meeting up with 2 reports" 114 | assert manager_max.do_relax() == "Max Doe is taking a trip to the Bahamas" 115 | assert manager_max.do_hire() == "Max Doe is hiring employees" 116 | 117 | 118 | if __name__ == "__main__": 119 | main() 120 | -------------------------------------------------------------------------------- /ultimatepython/classes/basic_class.py: -------------------------------------------------------------------------------- 1 | """ 2 | A class is made up of methods and state. This allows code and data to be 3 | combined as one logical entity. This module defines a basic car class, 4 | creates a car instance and uses it for demonstration purposes. 5 | """ 6 | from inspect import isfunction, ismethod, signature 7 | 8 | 9 | class Car: 10 | """Basic definition of a car. 11 | 12 | We begin with a simple mental model of what a car is. That way, we 13 | can start exploring the core concepts that are associated with a 14 | class definition. 15 | """ 16 | 17 | def __init__(self, make, model, year, miles): 18 | """Constructor logic.""" 19 | self.make = make 20 | self.model = model 21 | self.year = year 22 | self.miles = miles 23 | 24 | def __repr__(self): 25 | """Formal representation for developers.""" 26 | return f"