diff --git a/Pytorch_Basic/.gitignore b/Deeplearning_with_Pytorch/.gitignore similarity index 100% rename from Pytorch_Basic/.gitignore rename to Deeplearning_with_Pytorch/.gitignore diff --git a/Pytorch_Basic/deeplearning_computation.ipynb b/Deeplearning_with_Pytorch/Deeplearning_Computation.ipynb similarity index 100% rename from Pytorch_Basic/deeplearning_computation.ipynb rename to Deeplearning_with_Pytorch/Deeplearning_Computation.ipynb diff --git a/Pytorch_Basic/probability.ipynb b/Deeplearning_with_Pytorch/Probability.ipynb similarity index 100% rename from Pytorch_Basic/probability.ipynb rename to Deeplearning_with_Pytorch/Probability.ipynb diff --git a/Pytorch_Basic/automatic_differentiation.ipynb b/Deeplearning_with_Pytorch/automatic_differentiation.ipynb similarity index 100% rename from Pytorch_Basic/automatic_differentiation.ipynb rename to Deeplearning_with_Pytorch/automatic_differentiation.ipynb diff --git a/Pytorch_Basic/linear_regression.ipynb b/Deeplearning_with_Pytorch/linear_regression.ipynb similarity index 100% rename from Pytorch_Basic/linear_regression.ipynb rename to Deeplearning_with_Pytorch/linear_regression.ipynb diff --git a/Pytorch_Basic/mlp.params b/Deeplearning_with_Pytorch/mlp.params similarity index 100% rename from Pytorch_Basic/mlp.params rename to Deeplearning_with_Pytorch/mlp.params diff --git a/Pytorch_Basic/mydict b/Deeplearning_with_Pytorch/mydict similarity index 100% rename from Pytorch_Basic/mydict rename to Deeplearning_with_Pytorch/mydict diff --git a/Pytorch_Basic/x-file b/Deeplearning_with_Pytorch/x-file similarity index 100% rename from Pytorch_Basic/x-file rename to Deeplearning_with_Pytorch/x-file diff --git a/Pytorch_Basic/x-files b/Deeplearning_with_Pytorch/x-files similarity index 100% rename from Pytorch_Basic/x-files rename to Deeplearning_with_Pytorch/x-files diff --git a/Module_and_Package/test/test_array.py b/Module_and_Package/tests/test_array.py similarity index 100% rename from Module_and_Package/test/test_array.py rename to Module_and_Package/tests/test_array.py diff --git a/Module_and_Package/upload_package/.gitignore b/Module_and_Package/upload_package/.gitignore deleted file mode 100644 index 5b6294e..0000000 --- a/Module_and_Package/upload_package/.gitignore +++ /dev/null @@ -1,140 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Temp files -*~ -~* -.*~ -\#* -.#* -*# - -# Distribution / packaging -.Python -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -wheels/ -*.egg-info/ -.installed.cfg -*.egg -MANIFEST - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*.cover -.hypothesis/ -.pytest_cache/ -*.mp4 - -# Performance profiling -prof/ -*.cprof - -# Debian Files -debian/files -debian/python-beaver* - -# Sphinx build -doc/_build - -# Generated man page -doc/aws_hostname.1 - -_run.py -_devfiles/* - -_build -_static -_templates -_autosummary -.pytest_cache* - -.vscode/ - -# mkdocs documentation -/site - -# mypy -.mypy_cache/ - -# Mac -.DS_Store -.AppleDouble -.LSOverride - -# Icon must end with two \r -Icon? -Icon - - -# Thumbnails -._* - -# Files that might appear in the root of a volume -.DocumentRevisions-V100 -.fseventsd -.Spotlight-V100 -.TemporaryItems -.Trashes -.VolumeIcon.icns -.com.apple.timemachine.donotpresent - -# Directories potentially created on remote AFP share -.AppleDB -.AppleDesktop -Network Trash Folder -Temporary Items -.apdisk - -.dropbox - -# Generated -test/**/*.xml -/*.gv -/*.dot -/*.xml - -# PyCharm -.idea/ -.idea/workspace.xml -.idea/usage.statistics.xml -.idea/tasks.xml -.idea/modules.xml -.idea/*.iml - -# Additional IDE files -*.sublime-project - -# Common virtual environments -venv/ -env/ \ No newline at end of file diff --git a/Module_and_Package/upload_package/LICENSE b/Module_and_Package/upload_package/LICENSE deleted file mode 100644 index 5a644f4..0000000 --- a/Module_and_Package/upload_package/LICENSE +++ /dev/null @@ -1,20 +0,0 @@ -Copyright (c) 2024 SeoyoungOh - -Permission is hereby granted, free of charge, to any person obtaining a copy of -this software and associated documentation files (the "Software"), to deal in -the Software without restriction, including without limitation the rights to -use, copy, modify, merge, publish, distribute, sub-license, and/or sell copies -of the Software, and to permit persons to whom the Software is furnished to do -so, subject to the following conditions: - -The above copyright notice, and every other copyright notice found in this -software, and all the attributions in every file, and this permission notice -shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. \ No newline at end of file diff --git a/Module_and_Package/upload_package/MANIFEST.in b/Module_and_Package/upload_package/MANIFEST.in deleted file mode 100644 index 0385206..0000000 --- a/Module_and_Package/upload_package/MANIFEST.in +++ /dev/null @@ -1,3 +0,0 @@ -include LICENSE -include README.md -include requirements.txt \ No newline at end of file diff --git a/Module_and_Package/upload_package/README.md b/Module_and_Package/upload_package/README.md deleted file mode 100644 index 69b94bf..0000000 --- a/Module_and_Package/upload_package/README.md +++ /dev/null @@ -1,29 +0,0 @@ -# my_package_name - -## Table of Contents - * [Installation](#installation) - * [Quick start](#quick-start) - * [Features](#features) - -## Installation - -Download using pip via pypi. - -```bash -$ pip install 'package' --upgrade - or -$ pip install git+'repository' -``` -(Mac/homebrew users may need to use ``pip3``) - - -## Quick start -```python - >>> from my_package_name.converter import GifConverter - >>> c = GifConverter("your original images path", 'your gif output path', (320,240)) - >>> c.convert_gif() -``` - -## Features - * Python library to convert single oder multiple frame gif images - * OpenCV does not support gif images. diff --git a/Module_and_Package/upload_package/my_package_name/__init__.py b/Module_and_Package/upload_package/my_package_name/__init__.py deleted file mode 100644 index 6c6f21b..0000000 --- a/Module_and_Package/upload_package/my_package_name/__init__.py +++ /dev/null @@ -1,9 +0,0 @@ -# -*- coding: utf-8 -*- -""" -My Package Name: a very serious Python library - -""" -__title__ = "my_package_name" -__author__ = "Seoyoung Oh" -__license__ = "MIT License" -__copyright__ = "Copyright 2024 SeoyoungOh" \ No newline at end of file diff --git a/Module_and_Package/upload_package/my_package_name/converter.py b/Module_and_Package/upload_package/my_package_name/converter.py deleted file mode 100644 index 8a7c4be..0000000 --- a/Module_and_Package/upload_package/my_package_name/converter.py +++ /dev/null @@ -1,39 +0,0 @@ -import glob -from PIL import Image - -class GifConverter: - def __init__(self, path_in=None, path_out=None, resize=(320,240)): - """ - path_in : Original path for the image files - path_out : Output path - resize : The size for resizing - """ - self.path_in = path_in or './*.png' - self.path_out = path_out or './output.gif' - self.resize = resize - - def convert_gif(self): - """ - GIF Image Conversion - """ - print(self.path_in, self.path_out, self.resize) - - img, *images = \ - [Image.open(f).resize(self.resize, Image.ANTIALIAS) for f in sorted(glob.glob(self.path_in))] - - try: - img.save( - fp=self.path_out, - format='GIF', - append_images=images, - save_all=True, - duration=500, - loop=0 - ) - except IOError: - print('Cannot convert!', img) - - -if __name__ == '__main__': - c = GifConverter('./project/images/*.png', './project/image_out/result.gif', (320,240)) - c.convert_gif() \ No newline at end of file diff --git a/Module_and_Package/upload_package/requirements.txt b/Module_and_Package/upload_package/requirements.txt deleted file mode 100644 index e69de29..0000000 diff --git a/Module_and_Package/upload_package/setup.cfg b/Module_and_Package/upload_package/setup.cfg deleted file mode 100644 index 224a779..0000000 --- a/Module_and_Package/upload_package/setup.cfg +++ /dev/null @@ -1,2 +0,0 @@ -[metadata] -description-file = README.md \ No newline at end of file diff --git a/Module_and_Package/upload_package/setup.py b/Module_and_Package/upload_package/setup.py deleted file mode 100644 index d5c3800..0000000 --- a/Module_and_Package/upload_package/setup.py +++ /dev/null @@ -1,22 +0,0 @@ -from setuptools import setup, find_packages - -setup( - name = 'my_package_name', - version = '1.0.0', - description = 'Test package for distribution', - author = 'standing-o', - author_email = 'osyoung540@gmail.com', - url = '', - download_url = '', - install_requires = ['pillow'], # AUTO INATALLATION - include_package_data=True, - packages=find_packages(), - keywords = [], - python_requires = '>=3', - zip_safe=False, - classifiers = [ - "Programming Language :: Python :: 3", - "License :: OSI Approved :: MIT License", - "Operating System :: OS Independent" - ] -) \ No newline at end of file diff --git a/Python_Advanced/context_manager.ipynb b/Python_Advanced/context_manager.ipynb deleted file mode 100644 index 4ebf194..0000000 --- a/Python_Advanced/context_manager.ipynb +++ /dev/null @@ -1,327 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e64b55e7", - "metadata": {}, - "source": [ - "# Context Manager\n", - "- A context manager in Python is responsible for allocating and releasing resources precisely at the desired time. \n", - "- It ensures that resources are set up when needed and then automatically cleaned up or released after use, even if an error occurs. " - ] - }, - { - "cell_type": "markdown", - "id": "a692b56f", - "metadata": {}, - "source": [ - "### With" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "db7c13d3", - "metadata": {}, - "outputs": [], - "source": [ - "file = open(\"./file1.txt\", 'w')\n", - "try:\n", - " file.write(\"Test1.\")\n", - "finally:\n", - " file.close()" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "e24a4cc9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['.gitignore', '.ipynb_checkpoints', 'context_manager.ipynb', 'copy.ipynb', 'file1.txt', 'functions.ipynb', 'method_overloading.ipynb', 'method_overriding.ipynb', 'property.ipynb', 'scope.ipynb']\n" - ] - } - ], - "source": [ - "import os\n", - "print(os.listdir())" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "78c2dbf4", - "metadata": {}, - "outputs": [], - "source": [ - "with open(\"./file2.txt\", 'w') as f:\n", - " f.write(\"Test2.\")" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "cdb58b1e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['.gitignore', '.ipynb_checkpoints', 'context_manager.ipynb', 'copy.ipynb', 'file1.txt', 'file2.txt', 'functions.ipynb', 'method_overloading.ipynb', 'method_overriding.ipynb', 'property.ipynb', 'scope.ipynb']\n" - ] - } - ], - "source": [ - "print(os.listdir())" - ] - }, - { - "cell_type": "markdown", - "id": "b0686c64", - "metadata": {}, - "source": [ - "### `__enter__`, `__exit__`" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "54c83489", - "metadata": {}, - "outputs": [], - "source": [ - "# Context manager with exception handling\n", - "\n", - "class FileWriter():\n", - " def __init__(self, file_name, method):\n", - " print(\"FileWriter started : __init__\")\n", - " self.file_obj = open(file_name, method)\n", - " \n", - " def __enter__(self):\n", - " print(\"FileWriter started : __enter__\")\n", - " return self.file_obj\n", - " \n", - " def __exit__(self, exc_type, value, trace_back):\n", - " print(\"FileWriter started : __exit__\")\n", - " if exc_type:\n", - " print(\"Logging exxception {}\".format((exc_type, value, trace_back)))\n", - " self.file_obj.close()" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "fd6930fc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "FileWriter started : __init__\n", - "FileWriter started : __enter__\n", - "FileWriter started : __exit__\n" - ] - } - ], - "source": [ - "# with -> init -> enter -> exit\n", - "with FileWriter('./file3.txt', 'w') as f:\n", - " f.write(\"Test3.\")" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "adc6698b", - "metadata": {}, - "outputs": [], - "source": [ - "# Contextlib: Measure execution\n", - "\n", - "import time\n", - "\n", - "class ExecuteTimer(object):\n", - " def __init__(self, msg):\n", - " self._msg = msg\n", - " \n", - " def __enter__(self):\n", - " self._start = time.monotonic()\n", - " return self._start\n", - " \n", - " # exit from `with`\n", - " def __exit__(self, exc_type, exc_value, exc_traceback):\n", - " if exc_type:\n", - " print(\"Logging exception {}\".format((exc_type, exc_value, exc_traceback)))\n", - " else:\n", - " print(\"{} : {} s\".format(self._msg, time.monotonic() - self._start))\n", - " return True" - ] - }, - { - "cell_type": "markdown", - "id": "321699cf", - "metadata": {}, - "source": [ - "- v: returned value of the `__enter__`" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "4473e2e5", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Received start monotonic1 : 1653231.328\n", - "Start... : 0.01500000013038516 s\n" - ] - } - ], - "source": [ - "with ExecuteTimer(\"Start...\") as v:\n", - " print(\"Received start monotonic1 : {}\".format(v))\n", - " # Execute job\n", - " for i in range(1000000):\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "b4523c13", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Received start monotonic1 : 1653243.078\n", - "Logging exception (, Exception('Raise...'), )\n" - ] - } - ], - "source": [ - "with ExecuteTimer(\"Start...\") as v:\n", - " print(\"Received start monotonic1 : {}\".format(v))\n", - " # Execute job\n", - " for i in range(1000000):\n", - " pass\n", - " raise Exception(\"Raise...\")" - ] - }, - { - "cell_type": "markdown", - "id": "c70f91ee", - "metadata": {}, - "source": [ - "### `__enter__`, `__exit__`, `@contextlib.contextmanager`" - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "76c9e1be", - "metadata": {}, - "outputs": [], - "source": [ - "import contextlib\n", - "import time\n", - "\n", - "# Same with `ExecuteTimer` class\n", - "@contextlib.contextmanager\n", - "def file_writer(file_name, method):\n", - " f = open(file_name, method)\n", - " yield f # __enter__\n", - " f.close() # __exit__\n", - " \n", - "with file_writer(\"file4.txt\", 'w') as f:\n", - " f.write(\"Test4\")" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "5f69f2a6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['.gitignore', '.ipynb_checkpoints', 'context_manager.ipynb', 'copy.ipynb', 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', 'functions.ipynb', 'method_overloading.ipynb', 'method_overriding.ipynb', 'property.ipynb', 'scope.ipynb']\n" - ] - } - ], - "source": [ - "print(os.listdir())" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "31b8486e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Received start monotonic2 : 1653286.031\n", - "Start... : 0.0s\n" - ] - } - ], - "source": [ - "# User decorator\n", - "\n", - "@contextlib.contextmanager\n", - "def ExecuteTimer_2(msg):\n", - " start = time.monotonic()\n", - " try: # __enter__\n", - " yield start\n", - " except BaseException as e:\n", - " print(\"Logging exception: {}: {}\".format(msg, e))\n", - " raise\n", - " else: # __exit__\n", - " print(\"{} : {}s\".format(msg, time.monotonic() - start))\n", - " \n", - "\n", - "with ExecuteTimer_2(\"Start...\") as v:\n", - " print(\"Received start monotonic2 : {}\".format(v))\n", - " for i in range(100):\n", - " pass\n", - "# raise ValueError(\"raise...\")" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/copy.ipynb b/Python_Advanced/copy.ipynb deleted file mode 100644 index 7e04516..0000000 --- a/Python_Advanced/copy.ipynb +++ /dev/null @@ -1,256 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "ecd245f6", - "metadata": {}, - "source": [ - "# Shallow Copy and Deep Copy\n", - "- Immutable | int, str, float, bool, unicode...\n", - "- Mmutable | list, set, dict" - ] - }, - { - "cell_type": "markdown", - "id": "47e7174b", - "metadata": {}, - "source": [ - "### Copy\n", - "- A simple assignment (e.g., new_list = original_list) doesn't create a new object but rather a new reference to the original. \n", - " - Changes to `new_list` affect `original_list`, as both references point to the same data." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "89beaf03", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2289645492224\n", - "2289645492224\n" - ] - } - ], - "source": [ - "# Call by value, Call by reference\n", - "\n", - "a_list = [1, 2, 3, [4, 5, 6], [7, 8, 9]]\n", - "b_list = a_list\n", - "\n", - "print(id(a_list))\n", - "print(id(b_list))" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "28cffd13", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 100, [4, 5, 6], [7, 8, 9]]\n", - "[1, 2, 100, [4, 5, 6], [7, 8, 9]]\n" - ] - } - ], - "source": [ - "b_list[2] = 100\n", - "print(a_list)\n", - "print(b_list)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "efa89e17", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 100, [4, 5, 100], [7, 8, 9]]\n", - "[1, 2, 100, [4, 5, 100], [7, 8, 9]]\n" - ] - } - ], - "source": [ - "b_list[3][2] = 100\n", - "print(a_list)\n", - "print(b_list)" - ] - }, - { - "cell_type": "markdown", - "id": "fb4580fe", - "metadata": {}, - "source": [ - "### Shallow Copy\n", - "- A shallow copy creates a new object but **copies only the references** of the elements from the original object \n", - "- For mutable types like lists, sets, and dictionaries, this means the top-level structure is duplicated, but nested objects are still referenced. Changes to nested objects will appear in both the original and the shallow copy." - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "8366745e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2289645274816\n", - "2289645670208\n" - ] - } - ], - "source": [ - "import copy\n", - "\n", - "c_list = [1, 2, 3, [4, 5, 6], [7, 8, 9]]\n", - "d_list = copy.copy(c_list)\n", - "\n", - "print(id(c_list))\n", - "print(id(d_list))" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "915f8044", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, [4, 5, 6], [7, 8, 9]]\n", - "[1, 100, 3, [4, 5, 6], [7, 8, 9]]\n" - ] - } - ], - "source": [ - "d_list[1] = 100\n", - "\n", - "print(c_list)\n", - "print(d_list)" - ] - }, - { - "cell_type": "markdown", - "id": "dafd06a0", - "metadata": {}, - "source": [ - "- Shallow copies of nested lists share references to the inner lists, not copies of them." - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "2dcb63ec", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, [4, 5, 6, 1000], [7, 10000, 9]]\n", - "[1, 100, 3, [4, 5, 6, 1000], [7, 10000, 9]]\n" - ] - } - ], - "source": [ - "d_list[3].append(1000)\n", - "d_list[4][1] = 10000\n", - "\n", - "print(c_list)\n", - "print(d_list)" - ] - }, - { - "cell_type": "markdown", - "id": "1e1a40cb", - "metadata": {}, - "source": [ - "### Deep Copy\n", - "- A **deep copy** creates a new object and recursively copies all nested elements, so even references within references are duplicated. \n", - "- For mutable objects, this ensures complete independence between the original and the copy, as all levels are fully copied. Changes to any part of the deep copy do not affect the original object." - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "219365cc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2289645023296\n", - "2289645787968\n" - ] - } - ], - "source": [ - "e_list = [1, 2, 3, [4, 5, 6], [7, 8, 9]]\n", - "f_list = copy.deepcopy(e_list)\n", - "\n", - "print(id(e_list))\n", - "print(id(f_list))" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "ba1efe94", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[1, 2, 3, [4, 5, 6], [7, 8, 9]]\n", - "[1, 2, 3, [4, 5, 6, 1000], [7, 10000, 9]]\n" - ] - } - ], - "source": [ - "f_list[3].append(1000)\n", - "f_list[4][1] = 10000\n", - "\n", - "print(e_list)\n", - "print(f_list)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/descriptor.ipynb b/Python_Advanced/descriptor.ipynb deleted file mode 100644 index f1be836..0000000 --- a/Python_Advanced/descriptor.ipynb +++ /dev/null @@ -1,319 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "8cfc0082", - "metadata": {}, - "source": [ - "# Descriptor\n", - "- A Python descriptor allows an object to have different objects as attribute values, with the ability to pre-define operations such as read, write, and delete. \n", - "- There are two types of descriptors: \n", - " - data descriptors (which include set and del methods) and non-data descriptors (which include the get method). \n", - "- Descriptors provide the advantage of creating read-only objects and allow classes to be created in a specific, intended manner." - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "91244ace", - "metadata": {}, - "outputs": [], - "source": [ - "class Descriptor_1(object):\n", - " def __init__(self, name='default'):\n", - " self.name = name\n", - " \n", - " def __get__(self, obj, objtype):\n", - " return f\"Get method called: {self}, {obj}, {objtype}\"\n", - " \n", - " def __set__(self, obj, name):\n", - " print(\"Set method called\")\n", - " if isinstance(name, str):\n", - " self.name = name\n", - " else:\n", - " raise TypeError(\"Name should be string.\")\n", - " \n", - " def __delete__(self, obj):\n", - " print(\"Delete method called\")\n", - " self.name = None\n", - " \n", - "class Sample_1(object):\n", - " name = Descriptor_1()" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "ee5d4ed2", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Set method called\n" - ] - } - ], - "source": [ - "s1 = Sample_1()\n", - "\n", - "s1.name = \"Test1\"" - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "49f2aca9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Set method called\n" - ] - }, - { - "ename": "TypeError", - "evalue": "Name should be string.", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_20408\\2548405504.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ms1\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mname\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;36m10\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_20408\\1241510678.py\u001b[0m in \u001b[0;36m__set__\u001b[1;34m(self, obj, name)\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mname\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mname\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 12\u001b[0m \u001b[1;32melse\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 13\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mTypeError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Name should be string.\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 14\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 15\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0m__delete__\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mobj\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", - "\u001b[1;31mTypeError\u001b[0m: Name should be string." - ] - } - ], - "source": [ - "s1.name = 10" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "016658ef", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "\"Get method called: <__main__.Descriptor_1 object at 0x000001E02DDDCA30>, <__main__.Sample_1 object at 0x000001E02E1D7370>, \"" - ] - }, - "execution_count": 19, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "s1.name" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "8896e818", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Delete method called\n" - ] - } - ], - "source": [ - "del s1.name" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "04cedaeb", - "metadata": {}, - "outputs": [], - "source": [ - "class Descriptor_2(object):\n", - " def __init__(self, value):\n", - " self._name = value\n", - " \n", - " def get_val(self):\n", - " return f\"Get method called: {self}, {self._name}\"\n", - " \n", - " def set_val(self, value):\n", - " print(\"Set method called\")\n", - " if isinstance(value, str):\n", - " self._name = value\n", - " else:\n", - " raise TypeError(\"Name should be string.\")\n", - " \n", - " def del_val(self):\n", - " print(\"Delete method called\")\n", - " self._name = None\n", - " \n", - " name = property(get_val, set_val, del_val, \"Property method example\")" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "a5cfbc5c", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Get method called: <__main__.Descriptor_2 object at 0x000001A26F381790>, Test2'" - ] - }, - "execution_count": 2, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "s2 = Descriptor_2(\"Test2\")\n", - "\n", - "s2.name" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "c336708d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Delete method called\n" - ] - } - ], - "source": [ - "del s2.name" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "b458caa7", - "metadata": {}, - "outputs": [ - { - "data": { - "text/plain": [ - "'Property method example'" - ] - }, - "execution_count": 4, - "metadata": {}, - "output_type": "execute_result" - } - ], - "source": [ - "Descriptor_2.name.__doc__" - ] - }, - { - "cell_type": "markdown", - "id": "717500f0", - "metadata": {}, - "source": [ - "### Low-level (Descriptor) vs High-level (Property)\n", - "- **Low-level (Descriptor)**\n", - " - A descriptor is a more fundamental concept in Python, and it's any object that implements at least one of the following methods: `__get__`, `__set__`, and `__delete__`. \n", - " - Descriptors provide a lot of control over how attributes are accessed, modified, or deleted, but they can be more complex to implement.\n", - "\n", - "- **High-level (Property)**\n", - " - The property function is a high-level interface that makes use of descriptors behind the scenes. \n", - " - Instead of creating a custom descriptor class, you can simply use `@property` to define a method as a getter, and optionally use `@.setter` and `@.deleter` to define setter and deleter methods. \n", - " - It gives you a simpler way to manage attribute access without directly dealing with descriptor mechanics." - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "42c506bf", - "metadata": {}, - "outputs": [], - "source": [ - "import os\n", - "\n", - "class FileCount:\n", - " def __get__(self, obj, objtype=None):\n", - " return len(os.listdir(obj.dirname))\n", - " \n", - "class Path:\n", - " size = FileCount()\n", - " \n", - " def __init__(self, dirname):\n", - " self.dirname = dirname" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "c93b704a", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "11\n" - ] - } - ], - "source": [ - "s = Path(\"./\")\n", - "print(s.size)" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "4c699ddf", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "9\n" - ] - } - ], - "source": [ - "g = Path(\"../\")\n", - "print(g.size)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/functions.ipynb b/Python_Advanced/functions.ipynb deleted file mode 100644 index cd26836..0000000 --- a/Python_Advanced/functions.ipynb +++ /dev/null @@ -1,242 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "8e48eecb", - "metadata": {}, - "source": [ - "# Functions\n", - "- Anonymous.\n", - "- They exist temporarily in the heap memory and are discarded immediately after use.\n", - "- Lambda functions are often used in Pythonic code due to their concise syntax.\n", - "- Unlike regular functions, lambda functions are not stored for reuse in memory.\n", - "- Lambda functions are automatically garbage collected when their reference count drops to zero.\n", - " - Regular functions remain in memory to support reusability." - ] - }, - { - "cell_type": "markdown", - "id": "c478f9e7", - "metadata": {}, - "source": [ - "### **Lambda**" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "b352540f", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "170\n" - ] - } - ], - "source": [ - "cul = lambda a, b, c: a * b + c\n", - "print(cul(10, 15, 20))" - ] - }, - { - "cell_type": "markdown", - "id": "a218d7b5", - "metadata": {}, - "source": [ - "### **Map**" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "033c4ae1", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]\n" - ] - } - ], - "source": [ - "digits_1 = [x * 10 for x in range(1, 11)]\n", - "print(digits_1)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "30960755", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100, 10000]\n" - ] - } - ], - "source": [ - "result = map(lambda i: i**2, digits_1)\n", - "print(result)\n", - "print(list(result))" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "61368dde", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[100, 400, 900, 1600, 2500, 3600, 4900, 6400, 8100, 10000]\n" - ] - } - ], - "source": [ - "def function_square(nums):\n", - " def double(x):\n", - " return x ** 2\n", - " return map(double, nums)\n", - "\n", - "print(list(function_square(digits_1)))" - ] - }, - { - "cell_type": "markdown", - "id": "421f3d19", - "metadata": {}, - "source": [ - "### Filter" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "ff7ee3fe", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 2, 4, 6, 8]\n" - ] - } - ], - "source": [ - "digits_2 = list(range(10))\n", - "\n", - "result = list(filter(lambda x: x%2 == 0, digits_2))\n", - "print(result)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "3ca282f9", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "[0, 2, 4, 6, 8]\n" - ] - } - ], - "source": [ - "def function_evens(nums):\n", - " def is_even(x):\n", - " return x % 2 == 0\n", - " return filter(is_even, nums)\n", - "\n", - "print(list(function_evens(digits_2)))" - ] - }, - { - "cell_type": "markdown", - "id": "d1123e36", - "metadata": {}, - "source": [ - "### **Reduce**" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "239ca9e6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5050\n" - ] - } - ], - "source": [ - "from functools import reduce\n", - "\n", - "digits_3 = [x for x in range(1, 101)]\n", - "result = reduce(lambda x, y: x + y, digits_3)\n", - "print(result)" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "96add847", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5050\n" - ] - } - ], - "source": [ - "def function_add(nums):\n", - " def add_(x, y):\n", - " return x + y\n", - " return reduce(add_, nums)\n", - "\n", - "print(function_add(digits_3))" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/meta_class.ipynb b/Python_Advanced/meta_class.ipynb deleted file mode 100644 index 62790e7..0000000 --- a/Python_Advanced/meta_class.ipynb +++ /dev/null @@ -1,564 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "6a37c7d0", - "metadata": {}, - "source": [ - "# Meta Class\n", - "- Classes are responsible for creation, and metaclasses allow for customizing classes to fit specific intentions. \n", - "- They are essential when building frameworks, as they enable dynamic creation (via type) and custom creation functions.\n", - "\n", - "- Custom classes, such as validation classes, can be created using metaclasses. \n", - "- Framework classes, when declared with a metaclass, enforce strict usage requirements for classes, such as requiring method overrides." - ] - }, - { - "cell_type": "markdown", - "id": "2196e529", - "metadata": {}, - "source": [ - "### Class of Class" - ] - }, - { - "cell_type": "code", - "execution_count": 17, - "id": "d8c71b29", - "metadata": {}, - "outputs": [], - "source": [ - "class Sample_1: # Class == Object\n", - " pass" - ] - }, - { - "cell_type": "markdown", - "id": "b340b4c2", - "metadata": {}, - "source": [ - "- Can be assigned to variables, copied, have new attributes added, and passed as function arguments." - ] - }, - { - "cell_type": "code", - "execution_count": 18, - "id": "fb5c45c6", - "metadata": {}, - "outputs": [], - "source": [ - "obj_1 = Sample_1()" - ] - }, - { - "cell_type": "code", - "execution_count": 19, - "id": "0d244d8c", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], - "source": [ - "print(obj_1.__class__)" - ] - }, - { - "cell_type": "markdown", - "id": "77087b57", - "metadata": {}, - "source": [ - "- The prototype (meta) of all classes is type.\n", - " - Therefore, if we can adjust the type class, we can dynamically adjust classes." - ] - }, - { - "cell_type": "markdown", - "id": "f622b80b", - "metadata": {}, - "source": [ - "```\n", - "obj_1 : Sample_1 Instance\n", - "Sample_1 : Type meta class\n", - "type : Type meta class\n", - "```" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "e61f829e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], - "source": [ - "print(obj_1.__class__.__class__)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "d6eac2eb", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "True\n" - ] - } - ], - "source": [ - "print(obj_1.__class__ is type(obj_1))" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "7c9bab48", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "True\n" - ] - } - ], - "source": [ - "print(obj_1.__class__.__class__ is type(obj_1).__class__)" - ] - }, - { - "cell_type": "markdown", - "id": "d6cab95a", - "metadata": {}, - "source": [ - "- type is itself a metaclass." - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "44f58107", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], - "source": [ - "print(type.__class__)" - ] - }, - { - "cell_type": "code", - "execution_count": 20, - "id": "93b71df7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "True\n", - "\n", - "\n", - "True\n", - "\n", - "\n", - "True\n" - ] - } - ], - "source": [ - "n = 10\n", - "d = {\"a\": 10, \"b\": 20}\n", - "\n", - "class Sample_2:\n", - " pass\n", - "\n", - "obj_2 = Sample_2()\n", - "\n", - "for o in (n, d, obj_2):\n", - " print(type(o))\n", - " print(o.__class__.__class__)\n", - " print(type(o) is o.__class__)" - ] - }, - { - "cell_type": "code", - "execution_count": 21, - "id": "1e1d26d6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\n", - "\n" - ] - } - ], - "source": [ - "for t in int, float, list, tuple:\n", - " print(type(t))" - ] - }, - { - "cell_type": "code", - "execution_count": 22, - "id": "53732735", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n" - ] - } - ], - "source": [ - "print(type(type))" - ] - }, - { - "cell_type": "markdown", - "id": "a95b7ada", - "metadata": {}, - "source": [ - "### Dynamic Metaclass\n", - "- Dynamic creation of metaclasses is important. \n", - "- A dynamically created metaclass allows for the creation of custom metaclasses, providing a significant advantage by enabling direct involvement in the class creation process according to specific intentions." - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "f5def6ec", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\n", - "{'__module__': '__main__', '__dict__': , '__weakref__': , '__doc__': None}\n" - ] - } - ], - "source": [ - "# Dynamic Creation\n", - "obj_3 = type(\"Sample_3\", (), {})\n", - "\n", - "print(obj_3)\n", - "print(type(obj_3))\n", - "print(obj_3.__base__)\n", - "print(obj_3.__dict__)" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "86e869f6", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "\n", - "\n", - "{'attr1': 100, 'attr2': 'text', '__module__': '__main__', '__doc__': None}\n", - "100 text\n" - ] - } - ], - "source": [ - "# Dynamic Creation and Inheritance\n", - "\n", - "class Parent_1:\n", - " pass\n", - "\n", - "obj_4 = type(\"Sample_4\", (Parent_1, ), dict(attr1=100, attr2=\"text\"))\n", - "\n", - "# class Sample_4(Parent_1):\n", - "# attr1 = 100\n", - "# attr2 = \"text\"\n", - "\n", - "print(obj_4)\n", - "print(type(obj_4))\n", - "print(obj_4.__base__)\n", - "print(obj_4.__dict__)\n", - "print(obj_4.attr1, obj_4.attr2)" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "34830216", - "metadata": {}, - "outputs": [], - "source": [ - "# Type dynamic class creation + method\n", - "\n", - "class Sample_5:\n", - " attr1 = 1\n", - " attr2 = 10\n", - " \n", - " def add(self, m, n):\n", - " return m + n\n", - " \n", - " def multiply(self, m, n):\n", - " return m * n\n", - " \n", - "obj_5 = Sample_5()" - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "b3a1d6ca", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "<__main__.Sample_5 object at 0x000002A4344165E0>\n", - "10\n", - "30\n", - "100\n" - ] - } - ], - "source": [ - "print(obj_5)\n", - "print(obj_5.attr2)\n", - "print(obj_5.add(10, 20))\n", - "print(obj_5.multiply(1, 100))" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "902c45f0", - "metadata": {}, - "outputs": [], - "source": [ - "obj_6 = type(\"Sample_6\", \n", - " (object, ), \n", - " dict(attr1=1, attr2 = 10, add = lambda x, y: x + y, multiply = lambda x, y: x * y)\n", - " )" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "0a4c49c0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "\n", - "1\n", - "30\n", - "100\n" - ] - } - ], - "source": [ - "print(obj_6)\n", - "print(obj_6.attr1)\n", - "print(obj_6.add(10, 20))\n", - "print(obj_6.multiply(1, 100))" - ] - }, - { - "cell_type": "markdown", - "id": "a2c0c97c", - "metadata": {}, - "source": [ - "### Type Inheritance\n", - "- Inheriting from a metaclass means inheriting from the type class and using the metaclass attribute. \n", - "- This allows for the creation of custom metaclasses." - ] - }, - { - "cell_type": "markdown", - "id": "adb60cab", - "metadata": {}, - "source": [ - "- Custom metaclass" - ] - }, - { - "cell_type": "code", - "execution_count": 35, - "id": "0fe81917", - "metadata": {}, - "outputs": [], - "source": [ - "def custom_multiply(self, d):\n", - " for i in range(len(self)):\n", - " self[i] = self[i] * d\n", - " \n", - "def custom_replace(self, old, new):\n", - " while old in self:\n", - " self[self.index(old)] = new" - ] - }, - { - "cell_type": "code", - "execution_count": 36, - "id": "f9546066", - "metadata": {}, - "outputs": [], - "source": [ - "Sample_7 = type(\"Sample_7\",\n", - " (list, ),\n", - " {\"desc\": \"list1\", \"custom_multiply\": custom_multiply, \"custom_replace\": custom_replace})" - ] - }, - { - "cell_type": "code", - "execution_count": 39, - "id": "539c0265", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['Hi', 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000]\n", - "list1\n" - ] - } - ], - "source": [ - "obj_7 = Sample_7([1,2,3,4,5,6,7,8,9])\n", - "obj_7.custom_multiply(1000)\n", - "obj_7.custom_replace(1000, \"Hi\")\n", - "\n", - "print(obj_7)\n", - "print(obj_7.desc)" - ] - }, - { - "cell_type": "markdown", - "id": "efe77d38", - "metadata": {}, - "source": [ - "- Custom metaclass with type inheritance\n", - " - Class intercept" - ] - }, - { - "cell_type": "code", - "execution_count": 44, - "id": "055caf90", - "metadata": {}, - "outputs": [], - "source": [ - "class Sample_8(type):\n", - " # Initialize generated instance\n", - " def __init__(self, object_or_name, bases, dict):\n", - " print(self, object_or_name, bases, dict)\n", - " super().__init__(object_or_name, bases, dict)\n", - " \n", - " # Execute instances\n", - " def __call__(self, *args, **kwargs):\n", - " print(self, *args, **kwargs)\n", - " return super().__call__(*args, **kwargs)\n", - " \n", - " # Generate class instance (Initialization of memory)\n", - " def __new__(meta_class, name, bases, namespace):\n", - " print(meta_class, name, bases, namespace)\n", - " namespace['desc'] = \"list2\"\n", - " namespace['custom_multiply'] = custom_multiply\n", - " namespace['custom_replace'] = custom_replace\n", - " \n", - " return type.__new__(meta_class, name, bases, namespace)" - ] - }, - { - "cell_type": "code", - "execution_count": 45, - "id": "9cac51c0", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - " list2-2 (,) {}\n", - " list2-2 (,) {'desc': 'list2', 'custom_multiply': , 'custom_replace': }\n", - " [1, 2, 3, 4, 5, 6, 7, 8, 9]\n", - "[7777, 2000, 3000, 4000, 5000, 6000, 7000, 8000, 9000]\n", - "list2\n" - ] - } - ], - "source": [ - "Sample_8_2 = Sample_8(\"list2-2\", (list, ), {})\n", - "obj_8 = Sample_8_2([1,2,3,4,5,6,7,8,9])\n", - "\n", - "obj_8.custom_multiply(1000)\n", - "obj_8.custom_replace(1000, 7777)\n", - "\n", - "print(obj_8)\n", - "print(obj_8.desc)" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/method_overloading.ipynb b/Python_Advanced/method_overloading.ipynb deleted file mode 100644 index ecb9d8a..0000000 --- a/Python_Advanced/method_overloading.ipynb +++ /dev/null @@ -1,229 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "1a94e508", - "metadata": {}, - "source": [ - "# Method Overloading\n", - "- **Python method overloading** allows a class to define multiple methods with the same name but with different parameters. \n", - " - This enables developers to redefine the behavior of a method based on the input arguments, making it flexible and adaptable to various situations.\n", - " \n", - "- By using the same method name for similar operations, developers can create a predictable API. Users can infer the functionality of a method based on its name, which enhances usability and helps prevent confusion.\n", - "\n", - "- **Method overloading** can lead to less code duplication. Instead of writing multiple methods with different names for similar tasks, you can use one method name with varying parameters, reducing redundancy and streamlining code management.\n", - "\n", - "- When methods are overloaded, it enhances code readability. \n", - "\n", - "- Developers can easily understand the intent of the code, as similar operations are grouped under a common method name, making it more intuitive.\n", - "\n", - "- **Method overloading** allows for a more flexible way to invoke methods based on the parameters provided. \n", - " - This capability enables a single method to handle different types and numbers of arguments, simplifying function calls and reducing the need for multiple distinct methods." - ] - }, - { - "cell_type": "markdown", - "id": "7b1508df", - "metadata": {}, - "source": [ - "- Using methods with the same name\n", - " - Dynamic type checking -> executed at runtime (type errors are discovered during execution)." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "a623ddc4", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassA():\n", - " \n", - " def add(self, x, y):\n", - " return x + y\n", - "\n", - " def add(self, x, y, z):\n", - " return x + y + z\n", - " \n", - " # Packing\n", - " # def add(self, *args):\n", - " # return sum(args)\n", - "\n", - "a = ClassA()" - ] - }, - { - "cell_type": "markdown", - "id": "a25f34c3", - "metadata": {}, - "source": [ - "- Python does not support method overloading\n", - " - **Multiple dispatch** allows you to define functions that can behave differently based on the types of the arguments passed to them." - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "2eec9dfd", - "metadata": {}, - "outputs": [ - { - "ename": "TypeError", - "evalue": "add() missing 1 required positional argument: 'z'", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_36428\\369765310.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m3\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[1;31mTypeError\u001b[0m: add() missing 1 required positional argument: 'z'" - ] - } - ], - "source": [ - "a.add(2,3)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "50bd46ac", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'add']\n" - ] - } - ], - "source": [ - "print(dir(a))" - ] - }, - { - "cell_type": "markdown", - "id": "66be7a1e", - "metadata": {}, - "source": [ - "- Branching based on data types" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "ed2cd117", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassB():\n", - " \n", - " def add(self, datatype, *args):\n", - " if datatype =='int': \n", - " return sum(args)\n", - "\n", - " if datatype =='str': \n", - " return ''.join([x for x in args])\n", - "\n", - "b = ClassB()" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "c7b435f4", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "11\n", - "Hi Geeks\n" - ] - } - ], - "source": [ - "print(b.add('int', 5, 6))\n", - "print(b.add('str', 'Hi ', 'Geeks'))" - ] - }, - { - "cell_type": "markdown", - "id": "d18424a6", - "metadata": {}, - "source": [ - "- Overloading with `multipledispatch`" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "e7a543c6", - "metadata": {}, - "outputs": [], - "source": [ - "from multipledispatch import dispatch\n", - "\n", - "class ClassC():\n", - " \n", - " @dispatch(int,int) \n", - " def product(x, y): \n", - " return x * y \n", - "\n", - " @dispatch(int,int,int) \n", - " def product(x, y, z): \n", - " return x * y * z\n", - "\n", - " @dispatch(float,float,float) \n", - " def product(x, y, z): \n", - " return x * y * z\n", - " \n", - "c = ClassC()" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "941df988", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "30\n", - "210\n", - "210.0\n" - ] - } - ], - "source": [ - "print(c.product(5, 6))\n", - "print(c.product(5, 6, 7))\n", - "print(c.product(5.0, 6.0, 7.0))" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/method_overriding.ipynb b/Python_Advanced/method_overriding.ipynb deleted file mode 100644 index 147c45a..0000000 --- a/Python_Advanced/method_overriding.ipynb +++ /dev/null @@ -1,217 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "eb551824", - "metadata": {}, - "source": [ - "# Method Overriding\n", - "- Method overriding in Python allows a `subclass` to redefine a method inherited from its `superclass`, providing an updated or customized implementation. \n", - "- This enables subclasses to call the superclass’s method directly before adding or modifying its behavior. \n", - "- By using structural approaches, such as abstracting methods in the parent class, overriding offers organized and extensible functionality. \n", - "- This practice supports polymorphism, as overridden methods can operate in varied ways based on the context of the subclass. \n", - "- Method overriding also improves readability and reduces errors by conserving method names, ultimately enhancing maintainability of the code." - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "e140b667", - "metadata": {}, - "outputs": [], - "source": [ - "class Parent_1():\n", - " def __init__(self):\n", - " self.value = 5\n", - "\n", - " def get_value(self):\n", - " return self.value\n", - "\n", - "class Child_1(ParentEx1):\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": 2, - "id": "00acf8cd", - "metadata": {}, - "outputs": [], - "source": [ - "c1 = Child_1()\n", - "p1 = Parent_1()" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "8abb0a42", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "5\n", - "['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_value', 'value']\n", - "\n", - "\n" - ] - } - ], - "source": [ - "print(c1.get_value())\n", - "print(dir(c1))\n", - "\n", - "print(Parent_1)\n", - "print(Child_1)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "ad7a1449", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "{'__module__': '__main__', '__init__': , 'get_value': , '__dict__': , '__weakref__': , '__doc__': None}\n", - "{'__module__': '__main__', '__doc__': None}\n" - ] - } - ], - "source": [ - "# Namespace\n", - "print(Parent_1.__dict__)\n", - "print(Child_1.__dict__)" - ] - }, - { - "cell_type": "markdown", - "id": "5b985b8e", - "metadata": {}, - "source": [ - "- Re-definition" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "8b46c433", - "metadata": {}, - "outputs": [], - "source": [ - "class Parent_2():\n", - " def __init__(self):\n", - " self.value = 5\n", - "\n", - " def get_value(self):\n", - " return self.value\n", - "\n", - "class Child_2(ParentEx1):\n", - " def get_value(self):\n", - " return self.value * 10" - ] - }, - { - "cell_type": "code", - "execution_count": 8, - "id": "cf4aacc7", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "50\n" - ] - } - ], - "source": [ - "c2 = Child_2()\n", - "\n", - "print(c2.get_value())" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "931e18cf", - "metadata": {}, - "outputs": [], - "source": [ - "import datetime\n", - "\n", - "class Logger(object):\n", - " def log(self, msg):\n", - " print(msg)\n", - "\n", - "class TimestampLogger(Logger):\n", - " def log(self, msg):\n", - " message = \"{ts} {msg}\".format(ts=datetime.datetime.now(),\n", - " msg=msg)\n", - " # super().log(message)\n", - " super(TimestampLogger, self).log(message)\n", - "\n", - "class DateLogger(Logger):\n", - " def log(self, msg):\n", - " message = \"{ts} {msg}\".format(ts=datetime.datetime.now().strftime('%Y-%m-%d'),\n", - " msg=msg)\n", - " # super().log(message)\n", - " super(DateLogger, self).log(message)\n", - "\n", - "l = Logger()\n", - "t = TimestampLogger()\n", - "d = DateLogger()" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "fa9b6877", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Called logger.\n", - "None\n", - "2024-11-04 21:27:50.344563 Called timestamp logger.\n", - "None\n", - "2024-11-04 Called date logger.\n", - "None\n" - ] - } - ], - "source": [ - "print(l.log('Called logger.'))\n", - "print(t.log('Called timestamp logger.'))\n", - "print(d.log('Called date logger.'))" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/property.ipynb b/Python_Advanced/property.ipynb deleted file mode 100644 index dc16c51..0000000 --- a/Python_Advanced/property.ipynb +++ /dev/null @@ -1,538 +0,0 @@ -{ - "cells": [ - { - "cell_type": "markdown", - "id": "e4942cb2", - "metadata": {}, - "source": [ - "# Property\n", - "### Underscore\n", - "- **Underscores** serve as a convention for access control rather than strict **access modifiers**. \n", - "- A single underscore prefix `(_var)` indicates an internal attribute, which should be treated as non-public but is accessible if needed. \n", - "- A double underscore prefix `(__var)` invokes name mangling, which makes it harder to accidentally access this variable from outside its class, but it’s still accessible if accessed intentionally." - ] - }, - { - "cell_type": "markdown", - "id": "dffe624e", - "metadata": {}, - "source": [ - "- Unpacking" - ] - }, - { - "cell_type": "code", - "execution_count": 1, - "id": "609570df", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 3\n" - ] - } - ], - "source": [ - "x, _, y = (1, 2, 3)\n", - "print(x, y)" - ] - }, - { - "cell_type": "code", - "execution_count": 3, - "id": "ff4349cc", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 5\n" - ] - } - ], - "source": [ - "a, *_, b = (1, 2, 3, 4, 5)\n", - "print(a, b)" - ] - }, - { - "cell_type": "code", - "execution_count": 4, - "id": "8ab05631", - "metadata": {}, - "outputs": [ - { - "ename": "ValueError", - "evalue": "too many values to unpack (expected 3)", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_37316\\3920197345.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m(\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m2\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m3\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m4\u001b[0m\u001b[1;33m,\u001b[0m \u001b[1;36m5\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 2\u001b[0m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mb\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mi\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", - "\u001b[1;31mValueError\u001b[0m: too many values to unpack (expected 3)" - ] - } - ], - "source": [ - "a, i, b = (1, 2, 3, 4, 5)\n", - "print(a, b, i)" - ] - }, - { - "cell_type": "code", - "execution_count": 5, - "id": "fc9fe8aa", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1 5 [2, 3, 4]\n" - ] - } - ], - "source": [ - "a, *i, b = (1, 2, 3, 4, 5)\n", - "print(a, b, i)" - ] - }, - { - "cell_type": "code", - "execution_count": 6, - "id": "e4841e1d", - "metadata": {}, - "outputs": [], - "source": [ - "for _ in range(10):\n", - " pass" - ] - }, - { - "cell_type": "code", - "execution_count": 7, - "id": "0dc23dcd", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "0\n", - "1\n", - "2\n", - "3\n", - "4\n", - "5\n", - "6\n", - "7\n", - "8\n", - "9\n" - ] - } - ], - "source": [ - "for _, val in enumerate(range(10)):\n", - " print(val)" - ] - }, - { - "cell_type": "markdown", - "id": "e0f35941", - "metadata": {}, - "source": [ - "- **Access Modifier**\n", - " - `name` : public\n", - " - `_name` : protected\n", - " - `__name` : private\n", - " \n", - "- **Naming Mangling**\n", - " - Name mangling is a mechanism that alters the name of a variable with a double underscore prefix `(__var)` to make it more unique and less accessible from outside the class. \n", - " - This is done by prefixing the variable name with `_ClassName`, where ClassName is the name of the class in which it is defined.\n", - " - For example, a variable `__my_var` in class MyClass will be internally transformed to `_MyClass__my_var`, making it harder to accidentally access from outside the class but still accessible if needed. \n", - " - This helps avoid name conflicts in subclasses, providing a form of limited privacy.\n", - " \n", - "- **As a rule, variables prefixed with `__` should not be accessed from outside their defining class.**" - ] - }, - { - "cell_type": "markdown", - "id": "d5db2b21", - "metadata": {}, - "source": [ - "- Not use property" - ] - }, - { - "cell_type": "code", - "execution_count": 10, - "id": "2962632d", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "0\n" - ] - } - ], - "source": [ - "class ClassA:\n", - " def __init__(self):\n", - " self.x = 0\n", - " self.__y = 0\n", - " self._z = 0\n", - " \n", - "a = ClassA()\n", - "a.x = 1\n", - "\n", - "print(a.x)\n", - "print(a._z)" - ] - }, - { - "cell_type": "code", - "execution_count": 9, - "id": "c93ee073", - "metadata": {}, - "outputs": [ - { - "ename": "AttributeError", - "evalue": "'SampleA' object has no attribute '__y'", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mAttributeError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_37316\\289092542.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mprint\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0ma\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__y\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[1;31mAttributeError\u001b[0m: 'SampleA' object has no attribute '__y'" - ] - } - ], - "source": [ - "print(a.__y)" - ] - }, - { - "cell_type": "code", - "execution_count": 11, - "id": "3a73031b", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['_SampleA__y', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_z', 'x']\n" - ] - } - ], - "source": [ - "print(dir(a))" - ] - }, - { - "cell_type": "markdown", - "id": "f878c105", - "metadata": {}, - "source": [ - "- There is no enforcement of this rule." - ] - }, - { - "cell_type": "code", - "execution_count": 12, - "id": "7e57fb45", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "2\n" - ] - } - ], - "source": [ - "a._ClassA__y = 2\n", - "print(a._ClassA__y)" - ] - }, - { - "cell_type": "markdown", - "id": "96d7ce4b", - "metadata": {}, - "source": [ - "### Getter, Setter\n", - "- Although double underscore-prefixed variables should not be accessed outside their class, there’s no strict enforcement of this rule. \n", - "- To control access and modification of these variables, Python uses getters and setters, often implemented through the property decorator. \n", - "- This allows the developer to define controlled access methods that retrieve or modify the value of an attribute, supporting encapsulation without directly exposing the variable." - ] - }, - { - "cell_type": "code", - "execution_count": 13, - "id": "cabc676b", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassB:\n", - " def __init__(self):\n", - " self.x = 0\n", - " self.__y = 0 # _SampleB__y\n", - " \n", - " def get_y(self):\n", - " return self.__y\n", - " \n", - " def set_y(self, value):\n", - " self.__y = value" - ] - }, - { - "cell_type": "code", - "execution_count": 14, - "id": "3edd8d80", - "metadata": {}, - "outputs": [], - "source": [ - "b = ClassB()\n", - "\n", - "b.x = 1\n", - "b.set_y(2)" - ] - }, - { - "cell_type": "code", - "execution_count": 15, - "id": "70da4360", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "2\n" - ] - } - ], - "source": [ - "print(b.x)\n", - "print(b.get_y())" - ] - }, - { - "cell_type": "code", - "execution_count": 16, - "id": "b3a85452", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['_SampleB__y', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'get_y', 'set_y', 'x']\n" - ] - } - ], - "source": [ - "print(dir(b))" - ] - }, - { - "cell_type": "markdown", - "id": "23ed056a", - "metadata": {}, - "source": [ - "- Advantages of `@Property`\n", - " - It creates more pythonic code, enabling constraints on variables while providing the same effect as traditional getters and setters, enhancing code consistency. \n", - " - It facilitates encapsulation by making it easy to add validation and other checks. \n", - " - Properties allow alternative representations (exposing attributes while hiding internal details) and make it simpler to manage an attribute’s lifecycle and memory. \n", - " - Additionally, they improve interoperability with libraries designed to work seamlessly with getters and setters.\n", - " " - ] - }, - { - "cell_type": "code", - "execution_count": 23, - "id": "63f13088", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassC:\n", - " def __init__(self):\n", - " self.x = 0\n", - " self.__y = 0 # private\n", - " \n", - " @property\n", - " def y(self):\n", - " print(\"Called get method.\")\n", - " return self.__y\n", - " \n", - " @y.setter\n", - " def y(self, value):\n", - " print(\"Called set method.\")\n", - " self.__y = value\n", - " \n", - " @y.deleter\n", - " def y(self):\n", - " del self.__y" - ] - }, - { - "cell_type": "code", - "execution_count": 24, - "id": "9215d484", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "Called set method.\n" - ] - } - ], - "source": [ - "c = ClassC()\n", - "c.x = 1\n", - "c.y = 2" - ] - }, - { - "cell_type": "code", - "execution_count": 25, - "id": "64e9009e", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "1\n", - "Called get method.\n", - "2\n" - ] - } - ], - "source": [ - "print(c.x)\n", - "print(c.y)" - ] - }, - { - "cell_type": "code", - "execution_count": 26, - "id": "55db77c8", - "metadata": {}, - "outputs": [ - { - "name": "stdout", - "output_type": "stream", - "text": [ - "['_SampleC__y', '__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'x', 'y']\n" - ] - } - ], - "source": [ - "print(dir(c))" - ] - }, - { - "cell_type": "markdown", - "id": "1d2d6ec0", - "metadata": {}, - "source": [ - "- Add restrictions on property usage." - ] - }, - { - "cell_type": "code", - "execution_count": 27, - "id": "c6d7b425", - "metadata": {}, - "outputs": [], - "source": [ - "class ClassD:\n", - " def __init__(self):\n", - " self.x = 0\n", - " self.__y = 0 # private\n", - " \n", - " @property\n", - " def y(self):\n", - " return self.__y\n", - " \n", - " @y.setter\n", - " def y(self, value):\n", - " if value < 0:\n", - " raise ValueError(\"Input value must be greater than 0.\")\n", - " self.__y = value\n", - " \n", - " @y.deleter\n", - " def y(self):\n", - " del self.__y" - ] - }, - { - "cell_type": "code", - "execution_count": 30, - "id": "4c11becf", - "metadata": {}, - "outputs": [], - "source": [ - "d = ClassD()\n", - "\n", - "d.x = 1\n", - "d.y = 10" - ] - }, - { - "cell_type": "code", - "execution_count": 31, - "id": "14a80005", - "metadata": {}, - "outputs": [ - { - "ename": "ValueError", - "evalue": "Input value must be greater than 0.", - "output_type": "error", - "traceback": [ - "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", - "\u001b[1;31mValueError\u001b[0m Traceback (most recent call last)", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_37316\\2645067046.py\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0md\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0my\u001b[0m \u001b[1;33m=\u001b[0m \u001b[1;33m-\u001b[0m\u001b[1;36m5\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", - "\u001b[1;32m~\\AppData\\Local\\Temp\\ipykernel_37316\\3629938946.py\u001b[0m in \u001b[0;36my\u001b[1;34m(self, value)\u001b[0m\n\u001b[0;32m 11\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0my\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mself\u001b[0m\u001b[1;33m,\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 12\u001b[0m \u001b[1;32mif\u001b[0m \u001b[0mvalue\u001b[0m \u001b[1;33m<\u001b[0m \u001b[1;36m0\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m---> 13\u001b[1;33m \u001b[1;32mraise\u001b[0m \u001b[0mValueError\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m\"Input value must be greater than 0.\"\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 14\u001b[0m \u001b[0mself\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0m__y\u001b[0m \u001b[1;33m=\u001b[0m \u001b[0mvalue\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m 15\u001b[0m \u001b[1;33m\u001b[0m\u001b[0m\n", - "\u001b[1;31mValueError\u001b[0m: Input value must be greater than 0." - ] - } - ], - "source": [ - "d.y = -5" - ] - } - ], - "metadata": { - "kernelspec": { - "display_name": "Python 3 (ipykernel)", - "language": "python", - "name": "python3" - }, - "language_info": { - "codemirror_mode": { - "name": "ipython", - "version": 3 - }, - "file_extension": ".py", - "mimetype": "text/x-python", - "name": "python", - "nbconvert_exporter": "python", - "pygments_lexer": "ipython3", - "version": "3.9.13" - } - }, - "nbformat": 4, - "nbformat_minor": 5 -} diff --git a/Python_Advanced/scope.ipynb b/Python_Advanced/scope.ipynb index bd92b7b..13851fb 100644 --- a/Python_Advanced/scope.ipynb +++ b/Python_Advanced/scope.ipynb @@ -6,7 +6,7 @@ "metadata": {}, "source": [ "# Scope\n", - "### Local Variable & Global Variable\n", + "### 1. Local Variable & Global Variable\n", "- **`Global variables`** are primarily used for constants or **fixed values** that do not change. \n", " - Modifying global variables within local scopes is generally discouraged.\n", "- **`Local variables`** are limited to resolving logic within functions, with a lifecycle that ends when the function completes execution. " @@ -31,11 +31,11 @@ "source": [ "c = 40\n", "\n", - "def func_1():\n", + "def foobar():\n", " c = c + 10\n", " print(c)\n", " \n", - "func_1() " + "foobar() " ] }, { @@ -63,13 +63,13 @@ "source": [ "d = 40\n", "\n", - "def func_2():\n", + "def barfoo():\n", " global d\n", " \n", " d = d + 10\n", " print(d)\n", " \n", - "func_2() " + "barfoo() " ] }, { @@ -89,14 +89,14 @@ "metadata": {}, "outputs": [], "source": [ - "def func_outer():\n", + "def outer():\n", " e = 70\n", - " def func_inner():\n", + " def inner():\n", " e += 10\n", " print(e)\n", - " return func_inner\n", + " return inner\n", "\n", - "func = func_outer()\n", + "func = outer()\n", "func()" ] }, @@ -123,15 +123,15 @@ } ], "source": [ - "def func_outer_():\n", + "def outer_():\n", " f = 70\n", - " def func_inner_():\n", + " def inner_():\n", " nonlocal f\n", " f += 10\n", " print(f)\n", - " return func_inner_\n", + " return inner_\n", "\n", - "func_= func_outer_()\n", + "func_= outer_()\n", "func_()" ] }, @@ -189,13 +189,13 @@ } ], "source": [ - "def func_3(var):\n", + "def func(var):\n", " x = 10\n", " def printer():\n", " print(\"Printer Function\")\n", " print(locals())\n", " \n", - "func_3(\"Hi\")" + "func(\"Hi\")" ] }, { @@ -267,9 +267,9 @@ ], "metadata": { "kernelspec": { - "display_name": "Python 3 (ipykernel)", + "display_name": "dacon", "language": "python", - "name": "python3" + "name": "dacon" }, "language_info": { "codemirror_mode": { @@ -281,7 +281,7 @@ "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", - "version": "3.9.13" + "version": "3.8.17" } }, "nbformat": 4, diff --git a/README.md b/README.md index 65b1126..5d270ca 100644 --- a/README.md +++ b/README.md @@ -7,74 +7,15 @@     -## Python Basic -### 1. Basic Structure | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Basic/basic_structure.ipynb) -|No.|Contents|No.|Contents|No.|Contents| No. | Contents | -|------|---|---|---|---|---|-----|----------| -|1|Print|2|Variable|3|Function| 4 | Method | -|5|Formatting|6|List and Tuple|7|Dictionary| 8 | Set | -|9|Collection|10|Lambda Function|11|Copy| - | - | - -### 2. Standard Modules | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Basic/standard_modules.ipynb) -|No.|Contents|No.|Contents|No.|Contents| -|------|---|------|---|------|---| -|1|Random|2|Time|3|Calendar| -|4|Math|5|Statistics|6|Sys| - - -  -  -  - - -## Python Advanced -### Scope | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/scope.ipynb) -### Functions | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/functions.ipynb) -|No.| Contents |No.| Contents |No.| Contents | -|------|----------|------|----------|------|----------| -|1| Lambda |2| Filter |3| Reduce | - -### Copy | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/copy.ipynb) - -### Context Manager | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/context_manager.ipynb) - -|No.| Contents |No.| Contents |No.| Contents | -|------|-----------|------|------------|------|----------| -|1| `__enter__` |2| `__exit__` |3| With | - -### Property | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/property.ipynb) -|No.| Contents |No.| Contents |No.| Contents | No. | Contents | -|------|------------|------|--------------------|------|----------|-----|---------------| -|1| Underscore |2| Access Modifier |3| Naming Mangling | 4 | Getter/Setter | - - -### Polymorphism | [Code1](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/method_overrriding.ipynb), [Code2](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/method_overloading.ipynb) -|No.| Contents |No.| Contents |No.| Contents | -|------|-------------------|------|--------------------|------|----------| -|1| Method Overriding |2| Method Overloading |3| `multipledispatch` | - - -### Metaclass | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/meta_class.ipynb) - -### Descriptor | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Advanced/descriptor.ipynb) - -  -  -  ## Module and Packages | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/tree/master/Module_and_Package) - Structure of python project, Pip -- **Baseline of Python library** - - `__init__.py` - - Root | `README.md`, `setup.py`, `setup.cfg(optional)`, `LICENSE`, `MANIFEST.in` - - `pip install setuptools wheel` and Build up       -## Pytorch Basic | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/tree/master/Deeplearning_with_Pytorch) - +## Pytorch Deeplearning | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/tree/master/Deeplearning_with_Pytorch) - Differentiation, Probability, Neural Networks - Layers and Blocks, Parameter Management, Custom layers, File I/O, GPU @@ -82,11 +23,27 @@     +## Python Basic +### 1. Basic Structure | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Basic/basic_structure.ipynb) +|No.|Contents|No.|Contents|No.|Contents|No.|Contents| +|------|---|---|---|---|---|---|---| +|1|Print|2|Variable|3|Function|4|Method| +|5|Formatting|6|List and Tuple|7|Dictionary|8|Set| +|9|Collection|10|Lambda Function|11|Copy|12|| + +### 2.Standard Modules | [Code](https://github.com/OH-Seoyoung/Python_Toolbox/blob/master/Python_Basic/standard_modules.ipynb) +|No.|Contents|No.|Contents| +|------|---|------|---| +|1|Random|2|Time| +|3|Calendar|4|Math| +|5|Statistics|6|Sys| +  +  +  ## Reference ``` [1] 김상형,『파이썬 정복』, 한빛미디어(2018) [2] Dive into Deep Learning, http://d2l.ai/ -[3] 모두를 위한 파이썬: 필수 문법 배우기 Feat. 오픈소스 패키지 배포, http://inf.run/fdBMs ```