├── Chapter14 ├── classtemplate.py ├── classtemplateattr.py ├── classtemplatemethod.py ├── classtemplateinit.py ├── classtemplates.py ├── classgenerator.py └── codegenerator.py ├── Chapter16 ├── vegcounter.py ├── branch.py └── chapter16.ipynb ├── Chapter05 └── product.py ├── LICENSE ├── README.md ├── Chapter15 ├── execution_framework.ipynb ├── codegenerator.py ├── chapter15.ipynb ├── codegen_framework.ipynb └── automobile.csv ├── Chapter12 └── chapter 12.ipynb ├── Chapter01 └── chapter 1.ipynb ├── Chapter10 └── chapter 10.ipynb └── Chapter08 └── chapter8.ipynb /Chapter14/classtemplate.py: -------------------------------------------------------------------------------- 1 | class VegCounter: 2 | pass -------------------------------------------------------------------------------- /Chapter14/classtemplateattr.py: -------------------------------------------------------------------------------- 1 | class VegCounter: 2 | items = None 3 | countername = None 4 | billamount = None -------------------------------------------------------------------------------- /Chapter14/classtemplatemethod.py: -------------------------------------------------------------------------------- 1 | class VegCounter: 2 | 3 | def returnCart(self, *items): 4 | cartItems = [] 5 | for i in items: 6 | cartItems.append(i) 7 | return cartItems -------------------------------------------------------------------------------- /Chapter14/classtemplateinit.py: -------------------------------------------------------------------------------- 1 | class VegCounter: 2 | 3 | def __init__(self, *items): 4 | cartItems = [] 5 | for i in items: 6 | cartItems.append(i) 7 | self.items = cartItems -------------------------------------------------------------------------------- /Chapter14/classtemplates.py: -------------------------------------------------------------------------------- 1 | class VegCounter: 2 | pass 3 | 4 | class ElectronicsCounter: 5 | pass 6 | 7 | class PasadenaBranch: 8 | pass 9 | 10 | class VegasBranch: 11 | pass 12 | 13 | -------------------------------------------------------------------------------- /Chapter14/classgenerator.py: -------------------------------------------------------------------------------- 1 | class ElectronicCounter: 2 | TestItem = None 3 | 4 | def verifyCart(self, item, status): 5 | if status == 'Y': 6 | print('Test passed for', item) 7 | else: 8 | print('Get another', item) -------------------------------------------------------------------------------- /Chapter16/vegcounter.py: -------------------------------------------------------------------------------- 1 | def return_cart(*items): 2 | ''' 3 | This function returns the list of items added to the cart. 4 | items: input the cart items. Eg: 'pens', 'pencils' 5 | ''' 6 | cart_items = [] 7 | for i in items: 8 | cart_items.append(i) 9 | return cart_items -------------------------------------------------------------------------------- /Chapter05/product.py: -------------------------------------------------------------------------------- 1 | class Product: 2 | _product_id = 100902 3 | _product_name = 'Iphone X' 4 | _product_category = 'Electronics' 5 | _unit_price = 700 6 | 7 | def get_product(self): 8 | return self._product_id, self._product_name, self._product_category, self._unit_price 9 | 10 | -------------------------------------------------------------------------------- /Chapter16/branch.py: -------------------------------------------------------------------------------- 1 | class BranchMetaclass(type): 2 | ''' 3 | This is a meta class for ABC Megamart branch that adds an additional 4 | quality to the attributes of branch classes. 5 | Add this as only a meta class. 6 | There are no methods to inherit this class as a parent class or super class. 7 | ''' 8 | def __new__(classitself, classname, baseclasses, attributes): 9 | import inspect 10 | newattributes = {} 11 | for attribute, value in attributes.items(): 12 | if attribute.startswith("__"): 13 | newattributes[attribute] = value 14 | elif inspect.isfunction(value): 15 | newattributes['branch' + attribute.title()] = value 16 | else: 17 | newattributes[attribute] = value 18 | return type.__new__(classitself, classname, baseclasses, newattributes) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Packt 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 | -------------------------------------------------------------------------------- /Chapter14/codegenerator.py: -------------------------------------------------------------------------------- 1 | class CodeGenerator: 2 | def __init__(self, classname, attribute): 3 | self.classname = classname 4 | self.attribute = attribute 5 | 6 | def generatecode(self): 7 | classtemplate = '''class ''' +self.classname+ ''':'''+'''\n def __init__(self):''' + '\n '+''' self._'''+self.attribute+''' = None\n\n @property 8 | def test'''+self.attribute+'''(self):\n return self.test'''+self.attribute+'''\n\n @test'''+self.attribute+'''.getter 9 | def test'''+self.attribute+'''(self):\n print("get test'''+self.attribute+'''")\n return self._test'''+self.attribute+''' 10 | 11 | @test'''+self.attribute+'''.setter 12 | def test'''+self.attribute+'''(self, value): 13 | print("set test'''+self.attribute+'''") 14 | self._test'''+self.attribute+''' = value 15 | 16 | @test'''+self.attribute+'''.deleter 17 | def test'''+self.attribute+'''(self): 18 | print("del test'''+self.attribute+'''") 19 | del self._test'''+self.attribute+''' 20 | ''' 21 | import ast 22 | class_tree = ast.parse(classtemplate) 23 | 24 | actualclass = compile(class_tree, 'class_tree', 'exec') 25 | 26 | print(ast.unparse(class_tree)) 27 | print('\n') -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | # Metaprogramming with Python 5 | 6 | Metaprogramming with Python 7 | 8 | This is the code repository for [Metaprogramming with Python](https://www.packtpub.com/product/metaprogramming-with-python/9781838554651?utm_source=github&utm_medium=repository&utm_campaign=9781838554651), published by Packt. 9 | 10 | **A programmer's guide to writing reusable code to build smarter applications** 11 | 12 | ## What is this book about? 13 | Effective and reusable code makes your application development process seamless and easily maintainable. With Python, you will have access to advanced metaprogramming features that you can use to build high-performing applications. 14 | 15 | This book covers the following exciting features: 16 | * Understand the programming paradigm of metaprogramming and its need 17 | * Revisit the fundamentals of object-oriented programming 18 | * Define decorators and work with metaclasses 19 | * Employ introspection and reflection on your code 20 | * Apply generics, typing, and templates to enhance your code 21 | * Get to grips with the structure of your code through abstract syntax trees and the behavior through method resolution order 22 | * Create dynamic objects and generate dynamic code 23 | * Understand various design patterns and best practices 24 | 25 | If you feel this book is for you, get your [copy](https://www.amazon.com/dp/1838554653) today! 26 | 27 | https://www.packtpub.com/ 29 | 30 | ## Instructions and Navigations 31 | All of the code is organized into folders. For example, Chapter02. 32 | 33 | The code will look like the following: 34 | ``` 35 | actualclass = compile(class_tree, 'vegctr_tree', 'exec') 36 | actualclass 37 | ``` 38 | 39 | **Following is what you need for this book:** 40 | If you are an intermediate-level Python programmer looking to enhance your coding skills by developing reusable and advanced frameworks, then this book is for you. Basic knowledge of Python programming will help you get the most out of this learning journey. 41 | 42 | With the following software and hardware list you can run all code files present in the book (Chapter 1-16). 43 | ### Software and Hardware List 44 | | Chapter | Software required | OS required | 45 | | -------- | ------------------------------------ | ----------------------------------- | 46 | | 1-16 | Python 3 | Windows, Mac OS X, and Linux (Any) | 47 | | 1-16 | Anaconda | Windows, Mac OS X, and Linux (Any) | 48 | | 1-16 | Jupyter Notebook | Windows, Mac OS X, and Linux (Any) | 49 | 50 | We also provide a PDF file that has color images of the screenshots/diagrams used in this book. [Click here to download it](https://packt.link/LTQbb). 51 | 52 | ### Related products 53 | * Learn Python Programming [[Packt]](https://www.packt.com/product/programming/b17579-learn-python-programming/?utm_source=github&utm_medium=repository&utm_campaign=9781801073240) [[Amazon]](https://www.amazon.com/dp/1801815097) 54 | 55 | * Mastering Python [[Packt]](https://www.packt.com/product/programming/b15882-mastering-python/?utm_source=github&utm_medium=repository&utm_campaign=9781800568754) [[Amazon]](https://www.amazon.com/dp/1800207727) 56 | 57 | ## Get to Know the Author 58 | **Sulekha AloorRavi** 59 | is an engineer and a data scientist with a wide technical breadth and deep understanding of many technologies and systems. Her background has led her to advanced Python based application development in the field of artificial intelligence. She enjoys solving real-world business problems with technology and working with data science and business intelligence teams to deliver real value. 60 | She has 15+ years of experience in Software Engineering and worked with major IT solution providers and International Banks. She graduated with an engineering degree in Information Technology and later completed a post-graduation program in Big Data and Machine Learning. She also enjoys teaching Artificial Intelligence and Machine Learning. 61 | ### Download a free PDF 62 | 63 | If you have already purchased a print or Kindle version of this book, you can get a DRM-free PDF version at no cost.
Simply click on the link to claim your free PDF.
64 |

https://packt.link/free-ebook/9781838554651

-------------------------------------------------------------------------------- /Chapter15/execution_framework.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 16, 6 | "id": "8550828f", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import abccaragencylib as carsales" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 37, 16 | "id": "f0856710", 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "class Queue:\n", 21 | " def __init__(self, makeclass, styleclass, age):\n", 22 | " self.makeclass = makeclass\n", 23 | " self.styleclass = styleclass\n", 24 | " self.make = self.makeclass()\n", 25 | " self.style = self.styleclass()\n", 26 | " self.new = carsales.New()\n", 27 | " self.resale = carsales.Resale()\n", 28 | " self.age = age\n", 29 | " \n", 30 | " def pipeline(self):\n", 31 | " print('*********ABC Car Agency - Catalogue***********')\n", 32 | " self.make.print_catalogue()\n", 33 | " print('\\n')\n", 34 | " self.style.print_catalogue()\n", 35 | " print('\\n')\n", 36 | " print('New Car Price : ' + str(self.new.calculate_price(self.makeclass)))\n", 37 | " print('Resale Price : ' + str(self.resale.calculate_price(self.makeclass, self.age)))" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 38, 43 | "id": "c8be7485", 44 | "metadata": {}, 45 | "outputs": [], 46 | "source": [ 47 | "def run_facade(makeclass, styleclass, age):\n", 48 | " queue = Queue(makeclass, styleclass, age)\n", 49 | " queue.pipeline()" 50 | ] 51 | }, 52 | { 53 | "cell_type": "code", 54 | "execution_count": 39, 55 | "id": "2aca514e", 56 | "metadata": {}, 57 | "outputs": [ 58 | { 59 | "name": "stdout", 60 | "output_type": "stream", 61 | "text": [ 62 | "*********ABC Car Agency - Catalogue***********\n", 63 | "\u001b[5m\u001b[94mFuel Type : \u001b[5m\u001b[94mGas\n", 64 | "\u001b[5m\u001b[94mAspiration : \u001b[5m\u001b[94mStd\n", 65 | "\u001b[5m\u001b[94mNum Of Door : \u001b[5m\u001b[94mTwo\n", 66 | "\u001b[5m\u001b[94mDrive Wheels : \u001b[5m\u001b[94mRwd\n", 67 | "\u001b[5m\u001b[94mWheel Base : \u001b[5m\u001b[94m94.5\n", 68 | "\u001b[5m\u001b[94mLength : \u001b[5m\u001b[94m171.2\n", 69 | "\u001b[5m\u001b[94mWidth : \u001b[5m\u001b[94m65.5\n", 70 | "\u001b[5m\u001b[94mHeight : \u001b[5m\u001b[94m52.4\n", 71 | "\u001b[5m\u001b[94mCurb Weight : \u001b[5m\u001b[94m2823\n", 72 | "\u001b[5m\u001b[94mFuel System : \u001b[5m\u001b[94mMpfi\n", 73 | "\u001b[5m\u001b[94mCity Mpg : \u001b[5m\u001b[94m19\n", 74 | "\u001b[5m\u001b[94mHighway Mpg : \u001b[5m\u001b[94m26\n", 75 | "\n", 76 | "\n", 77 | "\u001b[5m\u001b[31mEngine Location : \u001b[5m\u001b[31mFront\n", 78 | "\u001b[5m\u001b[31mEngine Type : \u001b[5m\u001b[31mOhc\n", 79 | "\u001b[5m\u001b[31mNum Of Cylinders : \u001b[5m\u001b[31mFour\n", 80 | "\u001b[5m\u001b[31mEngine Size : \u001b[5m\u001b[31m97\n", 81 | "\u001b[5m\u001b[31mBore : \u001b[5m\u001b[31m3.15\n", 82 | "\u001b[5m\u001b[31mStroke : \u001b[5m\u001b[31m3.29\n", 83 | "\u001b[5m\u001b[31mCompression Ratio : \u001b[5m\u001b[31m9.4\n", 84 | "\u001b[5m\u001b[31mHorse Power : \u001b[5m\u001b[31m69\n", 85 | "\u001b[5m\u001b[31mPeak Rpm : \u001b[5m\u001b[31m5200\n", 86 | "\n", 87 | "\n", 88 | "New Car Price : 16500.0\n", 89 | "Resale Price : 9075.0\n" 90 | ] 91 | } 92 | ], 93 | "source": [ 94 | "run_facade(carsales.AlfaRomero1, carsales.Hatchback28, 3)" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 40, 100 | "id": "e72b8258", 101 | "metadata": {}, 102 | "outputs": [ 103 | { 104 | "name": "stdout", 105 | "output_type": "stream", 106 | "text": [ 107 | "*********ABC Car Agency - Catalogue***********\n", 108 | "\u001b[5m\u001b[94mFuel Type : \u001b[5m\u001b[94mGas\n", 109 | "\u001b[5m\u001b[94mAspiration : \u001b[5m\u001b[94mStd\n", 110 | "\u001b[5m\u001b[94mNum Of Door : \u001b[5m\u001b[94mTwo\n", 111 | "\u001b[5m\u001b[94mDrive Wheels : \u001b[5m\u001b[94mFwd\n", 112 | "\u001b[5m\u001b[94mWheel Base : \u001b[5m\u001b[94m93.7\n", 113 | "\u001b[5m\u001b[94mLength : \u001b[5m\u001b[94m157.3\n", 114 | "\u001b[5m\u001b[94mWidth : \u001b[5m\u001b[94m64.4\n", 115 | "\u001b[5m\u001b[94mHeight : \u001b[5m\u001b[94m50.8\n", 116 | "\u001b[5m\u001b[94mCurb Weight : \u001b[5m\u001b[94m1918\n", 117 | "\u001b[5m\u001b[94mFuel System : \u001b[5m\u001b[94m2Bbl\n", 118 | "\u001b[5m\u001b[94mCity Mpg : \u001b[5m\u001b[94m37\n", 119 | "\u001b[5m\u001b[94mHighway Mpg : \u001b[5m\u001b[94m41\n", 120 | "\n", 121 | "\n", 122 | "\u001b[5m\u001b[31mEngine Location : \u001b[5m\u001b[31mFront\n", 123 | "\u001b[5m\u001b[31mEngine Type : \u001b[5m\u001b[31mDohc\n", 124 | "\u001b[5m\u001b[31mNum Of Cylinders : \u001b[5m\u001b[31mSix\n", 125 | "\u001b[5m\u001b[31mEngine Size : \u001b[5m\u001b[31m258\n", 126 | "\u001b[5m\u001b[31mBore : \u001b[5m\u001b[31m3.63\n", 127 | "\u001b[5m\u001b[31mStroke : \u001b[5m\u001b[31m4.17\n", 128 | "\u001b[5m\u001b[31mCompression Ratio : \u001b[5m\u001b[31m8.1\n", 129 | "\u001b[5m\u001b[31mHorse Power : \u001b[5m\u001b[31m176\n", 130 | "\u001b[5m\u001b[31mPeak Rpm : \u001b[5m\u001b[31m4750\n", 131 | "\n", 132 | "\n", 133 | "New Car Price : 5389.0\n", 134 | "Resale Price : 1347.25\n" 135 | ] 136 | } 137 | ], 138 | "source": [ 139 | "run_facade(carsales.Mitsubishi24, carsales.Sedan16, 5)" 140 | ] 141 | }, 142 | { 143 | "cell_type": "code", 144 | "execution_count": null, 145 | "id": "e2504e78", 146 | "metadata": {}, 147 | "outputs": [], 148 | "source": [] 149 | } 150 | ], 151 | "metadata": { 152 | "kernelspec": { 153 | "display_name": "Python 3", 154 | "language": "python", 155 | "name": "python3" 156 | }, 157 | "language_info": { 158 | "codemirror_mode": { 159 | "name": "ipython", 160 | "version": 3 161 | }, 162 | "file_extension": ".py", 163 | "mimetype": "text/x-python", 164 | "name": "python", 165 | "nbconvert_exporter": "python", 166 | "pygments_lexer": "ipython3", 167 | "version": "3.9.5" 168 | } 169 | }, 170 | "nbformat": 4, 171 | "nbformat_minor": 5 172 | } 173 | -------------------------------------------------------------------------------- /Chapter15/codegenerator.py: -------------------------------------------------------------------------------- 1 | class CodeGenerator: 2 | 3 | def generate_meta(self): 4 | ast = __import__('ast') 5 | meta_template = ''' 6 | from abc import ABC, abstractmethod, ABCMeta 7 | class CarSpecs(type, metaclass = ABCMeta): 8 | def __new__(classitself, classname, baseclasses, attributes): 9 | newattributes = {} 10 | for attribute, value in attributes.items(): 11 | if attribute.startswith("__"): 12 | newattributes[attribute] = value 13 | elif type(value)==int or type(value)==float: 14 | newattributes[attribute] = {} 15 | newattributes[attribute]['feature'] = attribute.title().replace('_', ' ') 16 | newattributes[attribute]['info'] = str(value) 17 | newattributes[attribute]['type'] = 'NUMERIC' 18 | elif type(value)==str: 19 | newattributes[attribute] = {} 20 | newattributes[attribute]['feature'] = attribute.title().replace('_', ' ') 21 | newattributes[attribute]['info'] = value.title() 22 | newattributes[attribute]['type'] = 'VARCHAR' 23 | elif type(value)==bool: 24 | newattributes[attribute] = {} 25 | newattributes[attribute]['feature'] = attribute.title().replace('_', ' ') 26 | newattributes[attribute]['info'] = value.title() 27 | newattributes[attribute]['type'] = 'BOOLEAN' 28 | 29 | else: 30 | newattributes[attribute] = value 31 | return type.__new__(classitself, classname, baseclasses, newattributes) 32 | ''' 33 | meta_tree = ast.parse(meta_template) 34 | print(ast.unparse(meta_tree)) 35 | print('\n') 36 | 37 | def generate_car_catalogue(self): 38 | ast = __import__('ast') 39 | catalogue_template = ''' 40 | class CarCatalogue(metaclass = CarSpecs): 41 | @abstractmethod 42 | def define_color(self): 43 | pass 44 | 45 | @abstractmethod 46 | def print_catalogue(self): 47 | pass 48 | ''' 49 | catalogue_tree = ast.parse(catalogue_template) 50 | print(ast.unparse(catalogue_tree)) 51 | print('\n') 52 | 53 | def generate_carmake_code(self): 54 | ast = __import__('ast') 55 | carmake_template = ''' 56 | class CarMake(metaclass = CarSpecs): 57 | @abstractmethod 58 | def define_spec(self): 59 | pass 60 | ''' 61 | carmake_tree = ast.parse(carmake_template) 62 | print(ast.unparse(carmake_tree)) 63 | print('\n') 64 | 65 | def generate_bodystyle_parent(self): 66 | ast = __import__('ast') 67 | bodystyle_parent_template = ''' 68 | class BodyStyle(metaclass = CarSpecs): 69 | @abstractmethod 70 | def body_style_features(self): 71 | pass 72 | ''' 73 | bodystyle_parent_tree = ast.parse(bodystyle_parent_template) 74 | print(ast.unparse(bodystyle_parent_tree)) 75 | print('\n') 76 | 77 | def generate_salestype_code(self): 78 | ast = __import__('ast') 79 | saletype_template = ''' 80 | class SaleType(metaclass = CarSpecs): 81 | @abstractmethod 82 | def calculate_price(self): 83 | pass 84 | ''' 85 | salestype_tree = ast.parse(saletype_template) 86 | print(ast.unparse(salestype_tree)) 87 | print('\n') 88 | 89 | def generate_newsale_code(self): 90 | ast = __import__('ast') 91 | newsale_template = ''' 92 | class New(SaleType, CarCatalogue, metaclass = CarSpecs): 93 | def calculate_price(self, classname): 94 | car = classname() 95 | price = float(car.price['info']) 96 | return price 97 | ''' 98 | newsale_tree = ast.parse(newsale_template) 99 | print(ast.unparse(newsale_tree)) 100 | print('\n') 101 | 102 | def generate_resale_code(self): 103 | ast = __import__('ast') 104 | resale_template = ''' 105 | class Resale(SaleType, CarCatalogue, metaclass = CarSpecs): 106 | def calculate_price(self, classname, years): 107 | car = classname() 108 | depreciation = years * 0.15 109 | price = float(car.price['info']) * (1 - depreciation) 110 | return price 111 | ''' 112 | resale_tree = ast.parse(resale_template) 113 | print(ast.unparse(resale_tree)) 114 | print('\n') 115 | 116 | def generate_car_code(self, classname, carspecs): 117 | self.classname = classname 118 | self.carspecs = carspecs 119 | ast = __import__('ast') 120 | car_template = ''' 121 | class '''+self.classname+'''(CarMake, CarCatalogue, metaclass = CarSpecs): 122 | fuel_type = '''+"'"+self.carspecs['fuel_type']+"'"+''' 123 | aspiration = '''+"'"+self.carspecs['aspiration']+"'"+''' 124 | num_of_door = '''+"'"+self.carspecs['num_of_door']+"'"+''' 125 | drive_wheels = '''+"'"+self.carspecs['drive_wheels']+"'"+''' 126 | wheel_base = '''+"'"+self.carspecs['wheel_base']+"'"+''' 127 | length = '''+"'"+self.carspecs['length']+"'"+''' 128 | width = '''+"'"+self.carspecs['width']+"'"+''' 129 | height = '''+"'"+self.carspecs['height']+"'"+''' 130 | curb_weight = '''+"'"+self.carspecs['curb_weight']+"'"+''' 131 | fuel_system = '''+"'"+self.carspecs['fuel_system']+"'"+''' 132 | city_mpg = '''+"'"+self.carspecs['city_mpg']+"'"+''' 133 | highway_mpg = '''+"'"+self.carspecs['highway_mpg']+"'"+''' 134 | price = '''+"'"+self.carspecs['price']+"'"+''' 135 | 136 | def define_color(self): 137 | BOLD = '\33[5m' 138 | BLUE = '\033[94m' 139 | return BOLD + BLUE 140 | 141 | def define_spec(self): 142 | specs = [self.fuel_type, self.aspiration, self.num_of_door, self.drive_wheels, 143 | self.wheel_base, self.length, self.width, self.height, self.curb_weight, 144 | self.fuel_system, self.city_mpg, self.highway_mpg] 145 | return specs 146 | 147 | def print_catalogue(self): 148 | for i in self.define_spec(): 149 | print(self.define_color() + i['feature'], ": ", self.define_color() + i['info']) 150 | ''' 151 | 152 | car_tree = ast.parse(car_template) 153 | print(ast.unparse(car_tree)) 154 | print('\n') 155 | 156 | def generate_bodystyle_code(self, classname, carfeatures): 157 | self.classname = classname 158 | self.carfeatures = carfeatures 159 | ast = __import__('ast') 160 | bodystyle_template = ''' 161 | class '''+self.classname+'''(BodyStyle, CarCatalogue, metaclass = CarSpecs): 162 | engine_location = '''+"'"+self.carfeatures['engine_location']+"'"+''' 163 | engine_type = '''+"'"+self.carfeatures['engine_type']+"'"+''' 164 | num_of_cylinders = '''+"'"+self.carfeatures['num_of_cylinders']+"'"+''' 165 | engine_size = '''+"'"+self.carfeatures['engine_size']+"'"+''' 166 | bore = '''+"'"+self.carfeatures['bore']+"'"+''' 167 | stroke = '''+"'"+self.carfeatures['stroke']+"'"+''' 168 | compression_ratio = '''+"'"+self.carfeatures['compression_ratio']+"'"+''' 169 | horse_power = '''+"'"+self.carfeatures['horse_power']+"'"+''' 170 | peak_rpm = '''+"'"+self.carfeatures['peak_rpm']+"'"+''' 171 | 172 | def body_style_features(self): 173 | features = [self.engine_location, self.engine_type, self.num_of_cylinders, self.engine_size, 174 | self.bore, self.stroke, self.compression_ratio, self.horse_power, self.peak_rpm] 175 | return features 176 | 177 | def define_color(self): 178 | BOLD = '\33[5m' 179 | RED = '\033[31m' 180 | return BOLD + RED 181 | 182 | def print_catalogue(self): 183 | for i in self.body_style_features(): 184 | print(self.define_color() + i['feature'], ": ", self.define_color() + i['info']) 185 | ''' 186 | bodystyle_tree = ast.parse(bodystyle_template) 187 | print(ast.unparse(bodystyle_tree)) 188 | print('\n') -------------------------------------------------------------------------------- /Chapter15/chapter15.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "metadata": {}, 7 | "outputs": [], 8 | "source": [ 9 | "from abc import ABC, abstractmethod\n", 10 | "class CarSpecs(type, metaclass = ABCMeta):\n", 11 | " def __new__(classitself, classname, baseclasses, attributes): \n", 12 | " newattributes = {}\n", 13 | " for attribute, value in attributes.items():\n", 14 | " if attribute.startswith(\"__\"):\n", 15 | " newattributes[attribute] = value\n", 16 | " elif type(value)==int or type(value)==float:\n", 17 | " newattributes[attribute] = {}\n", 18 | " newattributes[attribute]['feature'] = attribute.title().replace('_', ' ')\n", 19 | " newattributes[attribute]['info'] = str(value)\n", 20 | " newattributes[attribute]['type'] = 'NUMERIC'\n", 21 | " elif type(value)==str:\n", 22 | " newattributes[attribute] = {}\n", 23 | " newattributes[attribute]['feature'] = attribute.title().replace('_', ' ')\n", 24 | " newattributes[attribute]['info'] = value.title()\n", 25 | " newattributes[attribute]['type'] = 'VARCHAR'\n", 26 | " elif type(value)==bool:\n", 27 | " newattributes[attribute] = {}\n", 28 | " newattributes[attribute]['feature'] = attribute.title().replace('_', ' ')\n", 29 | " newattributes[attribute]['info'] = value.title()\n", 30 | " newattributes[attribute]['type'] = 'BOOLEAN'\n", 31 | " \n", 32 | " else:\n", 33 | " newattributes[attribute] = value \n", 34 | " return type.__new__(classitself, classname, baseclasses, newattributes)" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": 2, 40 | "metadata": {}, 41 | "outputs": [], 42 | "source": [ 43 | "class CarCatalogue(metaclass = CarSpecs):\n", 44 | " @abstractmethod\n", 45 | " def define_color(self):\n", 46 | " pass\n", 47 | " \n", 48 | " @abstractmethod\n", 49 | " def print_catalogue(self):\n", 50 | " pass" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": 3, 56 | "metadata": {}, 57 | "outputs": [], 58 | "source": [ 59 | "class CarMake(metaclass = CarSpecs): \n", 60 | " @abstractmethod\n", 61 | " def define_spec(self):\n", 62 | " pass " 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": 4, 68 | "metadata": {}, 69 | "outputs": [], 70 | "source": [ 71 | "class AlfaRomeo(CarMake, CarCatalogue, metaclass = CarSpecs):\n", 72 | " fuel_type = 'gas'\n", 73 | " aspiration = 'standard'\n", 74 | " num_of_door = 'two'\n", 75 | " drive_wheels = 'rwd'\n", 76 | " wheel_base = 88.6\n", 77 | " length = 168.8\n", 78 | " width = 64.1\n", 79 | " height = 48.8\n", 80 | " curb_weight = 2548\n", 81 | " fuel_system = 'mpfi'\n", 82 | " city_mpg = 21\n", 83 | " highway_mpg = 27\n", 84 | " price = 13495\n", 85 | " \n", 86 | " def define_color(self):\n", 87 | " BOLD = '\\33[5m'\n", 88 | " BLUE = '\\033[94m'\n", 89 | " return BOLD + BLUE\n", 90 | " \n", 91 | " def define_spec(self):\n", 92 | " specs = [self.fuel_type, self.aspiration, self.num_of_door, self.drive_wheels, \n", 93 | " self.wheel_base, self.length, self.width, self.height, self.curb_weight,\n", 94 | " self.fuel_system, self.city_mpg, self.highway_mpg]\n", 95 | " return specs\n", 96 | " \n", 97 | " def print_catalogue(self):\n", 98 | " for i in self.define_spec():\n", 99 | " print(self.define_color() + i['feature'], \": \", self.define_color() + i['info']) " 100 | ] 101 | }, 102 | { 103 | "cell_type": "code", 104 | "execution_count": 5, 105 | "metadata": {}, 106 | "outputs": [], 107 | "source": [ 108 | "alfa = AlfaRomeo()" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": 6, 114 | "metadata": {}, 115 | "outputs": [ 116 | { 117 | "data": { 118 | "text/plain": [ 119 | "{'feature': 'Aspiration', 'info': 'Standard', 'type': 'VARCHAR'}" 120 | ] 121 | }, 122 | "execution_count": 6, 123 | "metadata": {}, 124 | "output_type": "execute_result" 125 | } 126 | ], 127 | "source": [ 128 | "alfa.aspiration" 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": 7, 134 | "metadata": {}, 135 | "outputs": [ 136 | { 137 | "name": "stdout", 138 | "output_type": "stream", 139 | "text": [ 140 | "\u001b[5m\u001b[94mFuel Type : \u001b[5m\u001b[94mGas\n", 141 | "\u001b[5m\u001b[94mAspiration : \u001b[5m\u001b[94mStandard\n", 142 | "\u001b[5m\u001b[94mNum Of Door : \u001b[5m\u001b[94mTwo\n", 143 | "\u001b[5m\u001b[94mDrive Wheels : \u001b[5m\u001b[94mRwd\n", 144 | "\u001b[5m\u001b[94mWheel Base : \u001b[5m\u001b[94m88.6\n", 145 | "\u001b[5m\u001b[94mLength : \u001b[5m\u001b[94m168.8\n", 146 | "\u001b[5m\u001b[94mWidth : \u001b[5m\u001b[94m64.1\n", 147 | "\u001b[5m\u001b[94mHeight : \u001b[5m\u001b[94m48.8\n", 148 | "\u001b[5m\u001b[94mCurb Weight : \u001b[5m\u001b[94m2548\n", 149 | "\u001b[5m\u001b[94mFuel System : \u001b[5m\u001b[94mMpfi\n", 150 | "\u001b[5m\u001b[94mCity Mpg : \u001b[5m\u001b[94m21\n", 151 | "\u001b[5m\u001b[94mHighway Mpg : \u001b[5m\u001b[94m27\n" 152 | ] 153 | } 154 | ], 155 | "source": [ 156 | "alfa.print_catalogue()" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 8, 162 | "metadata": {}, 163 | "outputs": [], 164 | "source": [ 165 | "alfa.fuel_type['info'] = 'Diesel'" 166 | ] 167 | }, 168 | { 169 | "cell_type": "code", 170 | "execution_count": 9, 171 | "metadata": {}, 172 | "outputs": [ 173 | { 174 | "data": { 175 | "text/plain": [ 176 | "[{'feature': 'Fuel Type', 'info': 'Diesel', 'type': 'VARCHAR'},\n", 177 | " {'feature': 'Aspiration', 'info': 'Standard', 'type': 'VARCHAR'},\n", 178 | " {'feature': 'Num Of Door', 'info': 'Two', 'type': 'VARCHAR'},\n", 179 | " {'feature': 'Drive Wheels', 'info': 'Rwd', 'type': 'VARCHAR'},\n", 180 | " {'feature': 'Wheel Base', 'info': '88.6', 'type': 'NUMERIC'},\n", 181 | " {'feature': 'Length', 'info': '168.8', 'type': 'NUMERIC'},\n", 182 | " {'feature': 'Width', 'info': '64.1', 'type': 'NUMERIC'},\n", 183 | " {'feature': 'Height', 'info': '48.8', 'type': 'NUMERIC'},\n", 184 | " {'feature': 'Curb Weight', 'info': '2548', 'type': 'NUMERIC'},\n", 185 | " {'feature': 'Fuel System', 'info': 'Mpfi', 'type': 'VARCHAR'},\n", 186 | " {'feature': 'City Mpg', 'info': '21', 'type': 'NUMERIC'},\n", 187 | " {'feature': 'Highway Mpg', 'info': '27', 'type': 'NUMERIC'}]" 188 | ] 189 | }, 190 | "execution_count": 9, 191 | "metadata": {}, 192 | "output_type": "execute_result" 193 | } 194 | ], 195 | "source": [ 196 | "alfa.define_spec()" 197 | ] 198 | }, 199 | { 200 | "cell_type": "code", 201 | "execution_count": 10, 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [ 205 | "class Audi(CarMake, CarCatalogue, metaclass = CarSpecs):\n", 206 | " fuel_type = 'gas'\n", 207 | " aspiration = 'standard'\n", 208 | " num_of_door = 'four'\n", 209 | " drive_wheels = 'fwd'\n", 210 | " wheel_base = 99.8\n", 211 | " length = 176.6\n", 212 | " width = 54.3\n", 213 | " height = 48.8\n", 214 | " curb_weight = 2337\n", 215 | " fuel_system = 'mpfi'\n", 216 | " city_mpg = 24\n", 217 | " highway_mpg = 30\n", 218 | " price = 13950\n", 219 | " \n", 220 | " def define_color(self):\n", 221 | " BOLD = '\\33[5m'\n", 222 | " GREEN = '\\033[32m'\n", 223 | " return BOLD + GREEN\n", 224 | " \n", 225 | " def define_spec(self):\n", 226 | " specs = [self.fuel_type, self.aspiration, self.num_of_door, self.drive_wheels, \n", 227 | " self.wheel_base, self.length, self.width, self.height, self.curb_weight,\n", 228 | " self.fuel_system, self.city_mpg, self.highway_mpg]\n", 229 | " return specs\n", 230 | " \n", 231 | " def print_catalogue(self):\n", 232 | " for i in self.define_spec():\n", 233 | " print(self.define_color() + i['feature'], \": \", self.define_color() + i['info']) " 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": 11, 239 | "metadata": {}, 240 | "outputs": [], 241 | "source": [ 242 | "audi = Audi()" 243 | ] 244 | }, 245 | { 246 | "cell_type": "code", 247 | "execution_count": 12, 248 | "metadata": {}, 249 | "outputs": [ 250 | { 251 | "name": "stdout", 252 | "output_type": "stream", 253 | "text": [ 254 | "\u001b[5m\u001b[32mFuel Type : \u001b[5m\u001b[32mGas\n", 255 | "\u001b[5m\u001b[32mAspiration : \u001b[5m\u001b[32mStandard\n", 256 | "\u001b[5m\u001b[32mNum Of Door : \u001b[5m\u001b[32mFour\n", 257 | "\u001b[5m\u001b[32mDrive Wheels : \u001b[5m\u001b[32mFwd\n", 258 | "\u001b[5m\u001b[32mWheel Base : \u001b[5m\u001b[32m99.8\n", 259 | "\u001b[5m\u001b[32mLength : \u001b[5m\u001b[32m176.6\n", 260 | "\u001b[5m\u001b[32mWidth : \u001b[5m\u001b[32m54.3\n", 261 | "\u001b[5m\u001b[32mHeight : \u001b[5m\u001b[32m48.8\n", 262 | "\u001b[5m\u001b[32mCurb Weight : \u001b[5m\u001b[32m2337\n", 263 | "\u001b[5m\u001b[32mFuel System : \u001b[5m\u001b[32mMpfi\n", 264 | "\u001b[5m\u001b[32mCity Mpg : \u001b[5m\u001b[32m24\n", 265 | "\u001b[5m\u001b[32mHighway Mpg : \u001b[5m\u001b[32m30\n" 266 | ] 267 | } 268 | ], 269 | "source": [ 270 | "audi.print_catalogue()" 271 | ] 272 | }, 273 | { 274 | "cell_type": "code", 275 | "execution_count": 13, 276 | "metadata": {}, 277 | "outputs": [], 278 | "source": [ 279 | "class BodyStyle(metaclass = CarSpecs):\n", 280 | " @abstractmethod\n", 281 | " def body_style_features(self):\n", 282 | " pass " 283 | ] 284 | }, 285 | { 286 | "cell_type": "code", 287 | "execution_count": 14, 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "class Sedan(BodyStyle, CarCatalogue, metaclass = CarSpecs):\n", 292 | " engine_location = 'front'\n", 293 | " engine_type = 'ohc'\n", 294 | " num_of_cylinders = 'four' \n", 295 | " engine_size = 109\n", 296 | " bore = 3.19\n", 297 | " stroke = 3.4\n", 298 | " compression_ratio = 10\n", 299 | " horse_power = 102\n", 300 | " peak_rpm = 5500\n", 301 | " \n", 302 | " def body_style_features(self):\n", 303 | " features = [self.engine_location, self.engine_type, self.num_of_cylinders, self.engine_size,\n", 304 | " self.bore, self.stroke, self.compression_ratio, self.horse_power, self.peak_rpm]\n", 305 | " return features \n", 306 | " \n", 307 | " def define_color(self):\n", 308 | " BOLD = '\\33[5m'\n", 309 | " RED = '\\033[31m'\n", 310 | " return BOLD + RED\n", 311 | " \n", 312 | " def print_catalogue(self):\n", 313 | " for i in self.body_style_features():\n", 314 | " print(self.define_color() + i['feature'], \": \", self.define_color() + i['info']) " 315 | ] 316 | }, 317 | { 318 | "cell_type": "code", 319 | "execution_count": 15, 320 | "metadata": {}, 321 | "outputs": [], 322 | "source": [ 323 | "sedan = Sedan()" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": 16, 329 | "metadata": {}, 330 | "outputs": [ 331 | { 332 | "name": "stdout", 333 | "output_type": "stream", 334 | "text": [ 335 | "\u001b[5m\u001b[31mEngine Location : \u001b[5m\u001b[31mFront\n", 336 | "\u001b[5m\u001b[31mEngine Type : \u001b[5m\u001b[31mOhc\n", 337 | "\u001b[5m\u001b[31mNum Of Cylinders : \u001b[5m\u001b[31mFour\n", 338 | "\u001b[5m\u001b[31mEngine Size : \u001b[5m\u001b[31m109\n", 339 | "\u001b[5m\u001b[31mBore : \u001b[5m\u001b[31m3.19\n", 340 | "\u001b[5m\u001b[31mStroke : \u001b[5m\u001b[31m3.4\n", 341 | "\u001b[5m\u001b[31mCompression Ratio : \u001b[5m\u001b[31m10\n", 342 | "\u001b[5m\u001b[31mHorse Power : \u001b[5m\u001b[31m102\n", 343 | "\u001b[5m\u001b[31mPeak Rpm : \u001b[5m\u001b[31m5500\n" 344 | ] 345 | } 346 | ], 347 | "source": [ 348 | "sedan.print_catalogue()" 349 | ] 350 | }, 351 | { 352 | "cell_type": "code", 353 | "execution_count": 17, 354 | "metadata": {}, 355 | "outputs": [], 356 | "source": [ 357 | "class SaleType(metaclass = CarSpecs):\n", 358 | " @abstractmethod\n", 359 | " def calculate_price(self):\n", 360 | " pass" 361 | ] 362 | }, 363 | { 364 | "cell_type": "code", 365 | "execution_count": 41, 366 | "metadata": {}, 367 | "outputs": [], 368 | "source": [ 369 | "class New(SaleType, CarCatalogue, metaclass = CarSpecs):\n", 370 | " def calculate_price(self, classname):\n", 371 | " car = classname()\n", 372 | " price = float(car.price['info'])\n", 373 | " return price" 374 | ] 375 | }, 376 | { 377 | "cell_type": "code", 378 | "execution_count": 42, 379 | "metadata": {}, 380 | "outputs": [], 381 | "source": [ 382 | "class Resale(SaleType, CarCatalogue, metaclass = CarSpecs):\n", 383 | " def calculate_price(self, classname, years):\n", 384 | " car = classname()\n", 385 | " depreciation = years * 0.15\n", 386 | " price = float(car.price['info']) * (1 - depreciation)\n", 387 | " return price" 388 | ] 389 | }, 390 | { 391 | "cell_type": "code", 392 | "execution_count": 43, 393 | "metadata": {}, 394 | "outputs": [], 395 | "source": [ 396 | "resale = Resale()" 397 | ] 398 | }, 399 | { 400 | "cell_type": "code", 401 | "execution_count": 44, 402 | "metadata": {}, 403 | "outputs": [ 404 | { 405 | "data": { 406 | "text/plain": [ 407 | "9765.0" 408 | ] 409 | }, 410 | "execution_count": 44, 411 | "metadata": {}, 412 | "output_type": "execute_result" 413 | } 414 | ], 415 | "source": [ 416 | "resale.calculate_price(Audi, 2)" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "execution_count": null, 422 | "metadata": {}, 423 | "outputs": [], 424 | "source": [] 425 | } 426 | ], 427 | "metadata": { 428 | "kernelspec": { 429 | "display_name": "Python 3", 430 | "language": "python", 431 | "name": "python3" 432 | }, 433 | "language_info": { 434 | "codemirror_mode": { 435 | "name": "ipython", 436 | "version": 3 437 | }, 438 | "file_extension": ".py", 439 | "mimetype": "text/x-python", 440 | "name": "python", 441 | "nbconvert_exporter": "python", 442 | "pygments_lexer": "ipython3", 443 | "version": "3.9.5" 444 | } 445 | }, 446 | "nbformat": 4, 447 | "nbformat_minor": 4 448 | } 449 | -------------------------------------------------------------------------------- /Chapter16/chapter16.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "d1b18c55", 6 | "metadata": {}, 7 | "source": [ 8 | "## Chapter 16" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "82d1a13f", 14 | "metadata": {}, 15 | "source": [ 16 | "### Indentation" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": null, 22 | "id": "6374be82", 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "class GreaterThan10Counter():\n", 27 | " def return_cart(self, *items):\n", 28 | " cart_items = []\n", 29 | " for i in items:\n", 30 | " cart_items.append(i)\n", 31 | " return cart_items" 32 | ] 33 | }, 34 | { 35 | "cell_type": "code", 36 | "execution_count": null, 37 | "id": "41f7f07d", 38 | "metadata": {}, 39 | "outputs": [], 40 | "source": [ 41 | "greater = GreaterThan10Counter()" 42 | ] 43 | }, 44 | { 45 | "cell_type": "code", 46 | "execution_count": null, 47 | "id": "7514874a", 48 | "metadata": {}, 49 | "outputs": [], 50 | "source": [ 51 | "cart = greater.return_cart('paper clips', 'blue pens', 'stapler', 'pencils', 'a4paper', 'a3paper', 'chart', 'sketch pens', 'canvas', 'water color', 'acrylic colors')" 52 | ] 53 | }, 54 | { 55 | "cell_type": "code", 56 | "execution_count": null, 57 | "id": "41e4a852", 58 | "metadata": {}, 59 | "outputs": [], 60 | "source": [ 61 | "cart = greater.return_cart('paper clips', 'blue pens', 'stapler', 'pencils', 'a4paper', 'a3paper', \n", 62 | "'chart', 'sketch pens', 'canvas', 'water color', 'acrylic colors')" 63 | ] 64 | }, 65 | { 66 | "cell_type": "code", 67 | "execution_count": null, 68 | "id": "c59fec51", 69 | "metadata": {}, 70 | "outputs": [], 71 | "source": [ 72 | "cart = greater.return_cart('paper clips', 'blue pens', 'stapler', 'pencils', 'a4paper', 'a3paper', \n", 73 | " 'chart', 'sketch pens', 'canvas', 'water color', 'acrylic colors')" 74 | ] 75 | }, 76 | { 77 | "cell_type": "markdown", 78 | "id": "08d30006", 79 | "metadata": {}, 80 | "source": [ 81 | "### Neat representation" 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "id": "ce845097", 88 | "metadata": {}, 89 | "outputs": [], 90 | "source": [ 91 | "def signature(branch):\n", 92 | " def footnote(*args):\n", 93 | " LOGO='\\33[43m'\n", 94 | " print(LOGO+'ABC Mega Mart')\n", 95 | " return branch(*args)\n", 96 | " return footnote" 97 | ] 98 | }, 99 | { 100 | "cell_type": "code", 101 | "execution_count": null, 102 | "id": "06e8cebf", 103 | "metadata": {}, 104 | "outputs": [], 105 | "source": [ 106 | "@signature\n", 107 | "def manager_manhattan(*args):\n", 108 | " GREEN='\\033[92m'\n", 109 | " SELECT='\\33[7m'\n", 110 | " for arg in args:\n", 111 | " print(SELECT+GREEN+str(arg))" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": null, 117 | "id": "0d66a59e", 118 | "metadata": {}, 119 | "outputs": [], 120 | "source": [ 121 | "manager_manhattan('John M','john.m@abcmegamart.com','40097 5th Main Street','Manhattan',\n", 122 | " 'New York City','New York',11007)" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": null, 128 | "id": "b1ecf16f", 129 | "metadata": {}, 130 | "outputs": [], 131 | "source": [ 132 | "def signature(branch):\n", 133 | " def footnote(*args):\n", 134 | " LOGO = '\\33[43m'\n", 135 | " print(LOGO + 'ABC Mega Mart')\n", 136 | " return branch(*args)\n", 137 | " return footnote" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "id": "d4129120", 144 | "metadata": {}, 145 | "outputs": [], 146 | "source": [ 147 | "@signature\n", 148 | "def manager_manhattan(*args):\n", 149 | " GREEN = '\\033[92m'\n", 150 | " SELECT = '\\33[7m'\n", 151 | " for arg in args:\n", 152 | " print(SELECT + GREEN + str(arg))" 153 | ] 154 | }, 155 | { 156 | "cell_type": "code", 157 | "execution_count": null, 158 | "id": "bc78a3a4", 159 | "metadata": {}, 160 | "outputs": [], 161 | "source": [ 162 | "manager_manhattan('John M', 'john.m@abcmegamart.com', '40097 5th Main Street', 'Manhattan',\n", 163 | " 'New York City', 'New York',11007)" 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "id": "7bc7530b", 169 | "metadata": {}, 170 | "source": [ 171 | "### Comments" 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "id": "449727d3", 178 | "metadata": {}, 179 | "outputs": [], 180 | "source": [ 181 | "class ExampleMetaClass1(type):\n", 182 | " def __new__(classitself, *args):\n", 183 | " print(\"class itself: \", classitself)\n", 184 | " print(\"Others: \", args)\n", 185 | " return type.__new__(classitself, *args)" 186 | ] 187 | }, 188 | { 189 | "cell_type": "code", 190 | "execution_count": null, 191 | "id": "d2959d73", 192 | "metadata": {}, 193 | "outputs": [], 194 | "source": [ 195 | "class ExampleClass1(metaclass = ExampleMetaClass1): \n", 196 | " int1 = 123 # int1 is assigned a value of 123\n", 197 | " str1 = 'test'\n", 198 | " \n", 199 | " def test():\n", 200 | " print('test')" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": null, 206 | "id": "6651437e", 207 | "metadata": {}, 208 | "outputs": [], 209 | "source": [ 210 | "class SingletonBilling: #This code covers Singleton design pattern\n", 211 | " billing_instance = None\n", 212 | " product_name = 'Dark Chocolate'\n", 213 | " unit_price = 6\n", 214 | " quantity = 4\n", 215 | " tax = 0.054\n", 216 | " \n", 217 | " def __init__(self):\n", 218 | " if SingletonBilling.billing_instance == None:\n", 219 | " SingletonBilling.billing_instance = self\n", 220 | " else:\n", 221 | " print(\"Billing can have only one instance\")\n", 222 | " \n", 223 | " def generate_bill(self):\n", 224 | " total = self.unit_price * self.quantity \n", 225 | " final_total = total + total*self.tax\n", 226 | " print('***********------------------**************')\n", 227 | " print('Product:', self.product_name)\n", 228 | " print('Total:',final_total)\n", 229 | " print('***********------------------**************')" 230 | ] 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "id": "2e510c3e", 235 | "metadata": {}, 236 | "source": [ 237 | "### Documentation string" 238 | ] 239 | }, 240 | { 241 | "cell_type": "code", 242 | "execution_count": null, 243 | "id": "8ccc4ccb", 244 | "metadata": {}, 245 | "outputs": [], 246 | "source": [ 247 | "import vegcounter as vc" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": null, 253 | "id": "8fcd75fa", 254 | "metadata": {}, 255 | "outputs": [], 256 | "source": [ 257 | "#Demo doctring\n", 258 | "vc.return_cart()" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": null, 264 | "id": "22a32b50", 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "vc.return_cart('pens', 'pencils')" 269 | ] 270 | }, 271 | { 272 | "cell_type": "markdown", 273 | "id": "5165dd29", 274 | "metadata": {}, 275 | "source": [ 276 | "### Documentation string for metaprogramming" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": 1, 282 | "id": "626a8fbf", 283 | "metadata": {}, 284 | "outputs": [], 285 | "source": [ 286 | "from branch import BranchMetaclass" 287 | ] 288 | }, 289 | { 290 | "cell_type": "code", 291 | "execution_count": 2, 292 | "id": "1970c642", 293 | "metadata": {}, 294 | "outputs": [ 295 | { 296 | "data": { 297 | "text/plain": [ 298 | "branch.BranchMetaclass" 299 | ] 300 | }, 301 | "execution_count": 2, 302 | "metadata": {}, 303 | "output_type": "execute_result" 304 | } 305 | ], 306 | "source": [ 307 | "#Demo doctring\n", 308 | "BranchMetaclass" 309 | ] 310 | }, 311 | { 312 | "cell_type": "markdown", 313 | "id": "e6ea5a7d", 314 | "metadata": {}, 315 | "source": [ 316 | "### Naming convention" 317 | ] 318 | }, 319 | { 320 | "cell_type": "markdown", 321 | "id": "8997384c", 322 | "metadata": {}, 323 | "source": [ 324 | "#### Class Name" 325 | ] 326 | }, 327 | { 328 | "cell_type": "markdown", 329 | "id": "255bcff0", 330 | "metadata": {}, 331 | "source": [ 332 | "##### Not preferred" 333 | ] 334 | }, 335 | { 336 | "cell_type": "code", 337 | "execution_count": 8, 338 | "id": "476e6f46", 339 | "metadata": {}, 340 | "outputs": [], 341 | "source": [ 342 | "class billing_counter:\n", 343 | " def __init__(self, productname, unitprice, quantity, tax):\n", 344 | " self.productname = productname\n", 345 | " self.unitprice = unitprice\n", 346 | " self.quantity = quantity\n", 347 | " self.tax = tax" 348 | ] 349 | }, 350 | { 351 | "cell_type": "markdown", 352 | "id": "01a1cf6d", 353 | "metadata": {}, 354 | "source": [ 355 | "##### Preferred" 356 | ] 357 | }, 358 | { 359 | "cell_type": "code", 360 | "execution_count": 9, 361 | "id": "975e051e", 362 | "metadata": {}, 363 | "outputs": [], 364 | "source": [ 365 | "class BillingCounter:\n", 366 | " def __init__(self, productname, unitprice, quantity, tax):\n", 367 | " self.productname = productname\n", 368 | " self.unitprice = unitprice\n", 369 | " self.quantity = quantity\n", 370 | " self.tax = tax" 371 | ] 372 | }, 373 | { 374 | "cell_type": "markdown", 375 | "id": "7eca8ce6", 376 | "metadata": {}, 377 | "source": [ 378 | "#### Variable name" 379 | ] 380 | }, 381 | { 382 | "cell_type": "markdown", 383 | "id": "5e5b6b92", 384 | "metadata": {}, 385 | "source": [ 386 | "##### Not preferred" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 11, 392 | "id": "2cee873f", 393 | "metadata": {}, 394 | "outputs": [], 395 | "source": [ 396 | "class BillingCounter:\n", 397 | " def __init__(self, PRODUCTNAME, UnitPrice, Quantity, TaX):\n", 398 | " self.PRODUCTNAME = PRODUCTNAME\n", 399 | " self.UnitPrice = UnitPrice\n", 400 | " self.Quantity = Quantity\n", 401 | " self.TaX = TaX" 402 | ] 403 | }, 404 | { 405 | "cell_type": "markdown", 406 | "id": "cb6ac6f8", 407 | "metadata": {}, 408 | "source": [ 409 | "##### Preferred - example 1" 410 | ] 411 | }, 412 | { 413 | "cell_type": "code", 414 | "execution_count": 12, 415 | "id": "e2b4ad64", 416 | "metadata": {}, 417 | "outputs": [], 418 | "source": [ 419 | "class BillingCounter:\n", 420 | " def __init__(self, product, unit, quantity, tax):\n", 421 | " self.product = product\n", 422 | " self.unit = unit\n", 423 | " self.quantity = quantity\n", 424 | " self.tax = tax" 425 | ] 426 | }, 427 | { 428 | "cell_type": "markdown", 429 | "id": "0c6ecb3f", 430 | "metadata": {}, 431 | "source": [ 432 | "##### Preferred - example 2" 433 | ] 434 | }, 435 | { 436 | "cell_type": "code", 437 | "execution_count": 13, 438 | "id": "1bff3bcd", 439 | "metadata": {}, 440 | "outputs": [], 441 | "source": [ 442 | "class BillingCounter:\n", 443 | " def __init__(self, product_name, unit_price, quantity, tax):\n", 444 | " self.product_name = product_name\n", 445 | " self.unit_price = unit_price\n", 446 | " self.quantity = quantity\n", 447 | " self.tax = tax" 448 | ] 449 | }, 450 | { 451 | "cell_type": "markdown", 452 | "id": "abae7973", 453 | "metadata": {}, 454 | "source": [ 455 | "#### Function or Method" 456 | ] 457 | }, 458 | { 459 | "cell_type": "markdown", 460 | "id": "356fd8e5", 461 | "metadata": {}, 462 | "source": [ 463 | "##### Not preferred" 464 | ] 465 | }, 466 | { 467 | "cell_type": "code", 468 | "execution_count": 17, 469 | "id": "778b59a1", 470 | "metadata": {}, 471 | "outputs": [], 472 | "source": [ 473 | "class TypeCheck:\n", 474 | " def Intcheck(self,inputvalue):\n", 475 | " if (type(inputvalue) != int) or (len(str(inputvalue)) > 2):\n", 476 | " return False\n", 477 | " else:\n", 478 | " return True\n", 479 | " \n", 480 | " def STRINGCHECK(self,inputvalue):\n", 481 | " if (type(inputvalue) != str) or (len(str(inputvalue)) > 10):\n", 482 | " return False\n", 483 | " else:\n", 484 | " return True\n", 485 | " " 486 | ] 487 | }, 488 | { 489 | "cell_type": "markdown", 490 | "id": "05663448", 491 | "metadata": {}, 492 | "source": [ 493 | "##### Preferred" 494 | ] 495 | }, 496 | { 497 | "cell_type": "code", 498 | "execution_count": 1, 499 | "id": "b38607c0", 500 | "metadata": {}, 501 | "outputs": [], 502 | "source": [ 503 | "class TypeCheck:\n", 504 | " def int_check(self,input_value):\n", 505 | " if (type(input_value) != int) or (len(str(input_value)) > 2):\n", 506 | " return False\n", 507 | " else:\n", 508 | " return True\n", 509 | " \n", 510 | " def string_check(self,input_value):\n", 511 | " if (type(input_value) != str) or (len(str(input_value)) > 10):\n", 512 | " return False\n", 513 | " else:\n", 514 | " return True\n", 515 | " " 516 | ] 517 | }, 518 | { 519 | "cell_type": "markdown", 520 | "id": "3642b276", 521 | "metadata": {}, 522 | "source": [ 523 | "### Don't reuse the names" 524 | ] 525 | }, 526 | { 527 | "cell_type": "code", 528 | "execution_count": 25, 529 | "id": "eec188e3", 530 | "metadata": {}, 531 | "outputs": [], 532 | "source": [ 533 | "class Branch:\n", 534 | " def maintenance_cost(self, product_type, quantity):\n", 535 | " self.product_type = product_type\n", 536 | " self.quantity = quantity\n", 537 | " cold_storage_cost = 100\n", 538 | " if (product_type == 'FMCG'):\n", 539 | " maintenance_cost = self.quantity * 0.25 + cold_storage_cost \n", 540 | " return maintenance_cost\n", 541 | " else:\n", 542 | " return \"We don't stock this product\"" 543 | ] 544 | }, 545 | { 546 | "cell_type": "code", 547 | "execution_count": 26, 548 | "id": "0365847e", 549 | "metadata": {}, 550 | "outputs": [], 551 | "source": [ 552 | "class Branch:\n", 553 | " def maintenance_cost(self, product_type, quantity):\n", 554 | " self.product_type = product_type\n", 555 | " self.quantity = quantity\n", 556 | " if (product_type == 'Electronics'):\n", 557 | " maintenance_cost = self.quantity * 0.05\n", 558 | " return maintenance_cost\n", 559 | " else:\n", 560 | " return \"We don't stock this product\"" 561 | ] 562 | }, 563 | { 564 | "cell_type": "code", 565 | "execution_count": 30, 566 | "id": "0497a464", 567 | "metadata": {}, 568 | "outputs": [ 569 | { 570 | "data": { 571 | "text/plain": [ 572 | "\"We don't stock this product\"" 573 | ] 574 | }, 575 | "execution_count": 30, 576 | "metadata": {}, 577 | "output_type": "execute_result" 578 | } 579 | ], 580 | "source": [ 581 | "branch = Branch()\n", 582 | "branch.maintenance_cost('FMCG', 1)" 583 | ] 584 | }, 585 | { 586 | "cell_type": "markdown", 587 | "id": "8786b67c", 588 | "metadata": {}, 589 | "source": [ 590 | "### Preferred" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": 23, 596 | "id": "82293f01", 597 | "metadata": {}, 598 | "outputs": [], 599 | "source": [ 600 | "class Brooklyn:\n", 601 | " def maintenance_cost(self, product_type, quantity):\n", 602 | " self.product_type = product_type\n", 603 | " self.quantity = quantity\n", 604 | " cold_storage_cost = 100\n", 605 | " if (product_type == 'FMCG'):\n", 606 | " maintenance_cost = self.quantity * 0.25 + cold_storage_cost \n", 607 | " return maintenance_cost\n", 608 | " else:\n", 609 | " return \"We don't stock this product\"" 610 | ] 611 | }, 612 | { 613 | "cell_type": "code", 614 | "execution_count": 24, 615 | "id": "11763def", 616 | "metadata": {}, 617 | "outputs": [], 618 | "source": [ 619 | "class Queens:\n", 620 | " def maintenance_cost(self, product_type, quantity):\n", 621 | " self.product_type = product_type\n", 622 | " self.quantity = quantity\n", 623 | " if (product_type == 'Electronics'):\n", 624 | " maintenance_cost = self.quantity * 0.05\n", 625 | " return maintenance_cost\n", 626 | " else:\n", 627 | " return \"We don't stock this product\"" 628 | ] 629 | }, 630 | { 631 | "cell_type": "code", 632 | "execution_count": 32, 633 | "id": "999c965e", 634 | "metadata": {}, 635 | "outputs": [ 636 | { 637 | "data": { 638 | "text/plain": [ 639 | "100.25" 640 | ] 641 | }, 642 | "execution_count": 32, 643 | "metadata": {}, 644 | "output_type": "execute_result" 645 | } 646 | ], 647 | "source": [ 648 | "brooklyn = Brooklyn()\n", 649 | "brooklyn.maintenance_cost('FMCG', 1)" 650 | ] 651 | }, 652 | { 653 | "cell_type": "code", 654 | "execution_count": 33, 655 | "id": "59c6f308", 656 | "metadata": {}, 657 | "outputs": [ 658 | { 659 | "data": { 660 | "text/plain": [ 661 | "0.05" 662 | ] 663 | }, 664 | "execution_count": 33, 665 | "metadata": {}, 666 | "output_type": "execute_result" 667 | } 668 | ], 669 | "source": [ 670 | "queens = Queens()\n", 671 | "queens.maintenance_cost('Electronics', 1)" 672 | ] 673 | } 674 | ], 675 | "metadata": { 676 | "kernelspec": { 677 | "display_name": "Python 3", 678 | "language": "python", 679 | "name": "python3" 680 | }, 681 | "language_info": { 682 | "codemirror_mode": { 683 | "name": "ipython", 684 | "version": 3 685 | }, 686 | "file_extension": ".py", 687 | "mimetype": "text/x-python", 688 | "name": "python", 689 | "nbconvert_exporter": "python", 690 | "pygments_lexer": "ipython3", 691 | "version": "3.9.5" 692 | } 693 | }, 694 | "nbformat": 4, 695 | "nbformat_minor": 5 696 | } 697 | -------------------------------------------------------------------------------- /Chapter15/codegen_framework.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "code", 5 | "execution_count": 1, 6 | "id": "8da7fbee", 7 | "metadata": {}, 8 | "outputs": [], 9 | "source": [ 10 | "import pandas as pd" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": 2, 16 | "id": "3f9f5f96", 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "auto = pd.read_csv(\"automobile.csv\")" 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": 3, 26 | "id": "0b29514a", 27 | "metadata": {}, 28 | "outputs": [], 29 | "source": [ 30 | "auto_truncated = auto.copy(deep=True)" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": 4, 36 | "id": "3a89e5a2", 37 | "metadata": {}, 38 | "outputs": [], 39 | "source": [ 40 | "auto_truncated.drop_duplicates(subset = ['make','body-style'], inplace = True)" 41 | ] 42 | }, 43 | { 44 | "cell_type": "code", 45 | "execution_count": 5, 46 | "id": "ce0c6f64", 47 | "metadata": {}, 48 | "outputs": [], 49 | "source": [ 50 | "auto_truncated.reset_index(inplace = True, drop = True)" 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": 6, 56 | "id": "f116e41b", 57 | "metadata": {}, 58 | "outputs": [], 59 | "source": [ 60 | "auto_truncated['make'] = auto_truncated['make'].apply(lambda x: x.title().replace('-',''))" 61 | ] 62 | }, 63 | { 64 | "cell_type": "code", 65 | "execution_count": 7, 66 | "id": "6d3694ab", 67 | "metadata": {}, 68 | "outputs": [], 69 | "source": [ 70 | "auto_truncated.reset_index(inplace = True)" 71 | ] 72 | }, 73 | { 74 | "cell_type": "code", 75 | "execution_count": 8, 76 | "id": "829abdc8", 77 | "metadata": {}, 78 | "outputs": [], 79 | "source": [ 80 | "auto_truncated['index'] = auto_truncated['index'].astype('str')" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": 9, 86 | "id": "60919ddc", 87 | "metadata": {}, 88 | "outputs": [], 89 | "source": [ 90 | "auto_truncated['make'] = auto_truncated['make'] + auto_truncated['index']" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": 10, 96 | "id": "a2522a1d", 97 | "metadata": {}, 98 | "outputs": [], 99 | "source": [ 100 | "auto_specs = auto_truncated[['make', 'fuel-type', 'aspiration', 'num-of-doors', 'drive-wheels', 'wheel-base',\n", 101 | " 'length', 'width', 'height', 'curb-weight', 'fuel-system', 'city-mpg', \n", 102 | " 'highway-mpg', 'price']].copy(deep = True)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "code", 107 | "execution_count": 11, 108 | "id": "923e4658", 109 | "metadata": {}, 110 | "outputs": [], 111 | "source": [ 112 | "auto_specs.columns = ['classname', 'fuel_type', 'aspiration', 'num_of_door', 'drive_wheels',\n", 113 | " 'wheel_base', 'length', 'width', 'height', 'curb_weight', 'fuel_system',\n", 114 | " 'city_mpg', 'highway_mpg', 'price' ]" 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": 12, 120 | "id": "b81f62de", 121 | "metadata": {}, 122 | "outputs": [], 123 | "source": [ 124 | "for col in auto_specs.columns:\n", 125 | " auto_specs[col] = auto_specs[col].astype('str')" 126 | ] 127 | }, 128 | { 129 | "cell_type": "code", 130 | "execution_count": 13, 131 | "id": "2d637933", 132 | "metadata": {}, 133 | "outputs": [], 134 | "source": [ 135 | "auto_truncated['body-style'] = auto_truncated['body-style'].apply(lambda x: x.title().replace('-',''))" 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": 14, 141 | "id": "70fdffab", 142 | "metadata": {}, 143 | "outputs": [], 144 | "source": [ 145 | "auto_truncated['body-style'] = auto_truncated['body-style'] + auto_truncated['index']" 146 | ] 147 | }, 148 | { 149 | "cell_type": "code", 150 | "execution_count": 15, 151 | "id": "4821741c", 152 | "metadata": {}, 153 | "outputs": [], 154 | "source": [ 155 | "auto_features = auto_truncated[['body-style', 'engine-location', 'engine-type', 'num-of-cylinders', 'engine-size', 'bore',\n", 156 | " 'stroke', 'compression-ratio', 'horsepower', 'peak-rpm']].copy(deep = True)" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 16, 162 | "id": "7de08327", 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "auto_features.columns = ['classname', 'engine_location', 'engine_type', 'num_of_cylinders', \n", 167 | " 'engine_size', 'bore', 'stroke', 'compression_ratio', 'horse_power', \n", 168 | " 'peak_rpm']" 169 | ] 170 | }, 171 | { 172 | "cell_type": "code", 173 | "execution_count": 17, 174 | "id": "b5d15c55", 175 | "metadata": {}, 176 | "outputs": [], 177 | "source": [ 178 | "for col in auto_features.columns:\n", 179 | " auto_features[col] = auto_features[col].astype('str')" 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": 19, 185 | "id": "178f2894", 186 | "metadata": {}, 187 | "outputs": [ 188 | { 189 | "data": { 190 | "text/plain": [ 191 | "(56, 14)" 192 | ] 193 | }, 194 | "execution_count": 19, 195 | "metadata": {}, 196 | "output_type": "execute_result" 197 | } 198 | ], 199 | "source": [ 200 | "auto_specs.shape" 201 | ] 202 | }, 203 | { 204 | "cell_type": "code", 205 | "execution_count": 18, 206 | "id": "d7509326", 207 | "metadata": {}, 208 | "outputs": [ 209 | { 210 | "data": { 211 | "text/html": [ 212 | "
\n", 213 | "\n", 226 | "\n", 227 | " \n", 228 | " \n", 229 | " \n", 230 | " \n", 231 | " \n", 232 | " \n", 233 | " \n", 234 | " \n", 235 | " \n", 236 | " \n", 237 | " \n", 238 | " \n", 239 | " \n", 240 | " \n", 241 | " \n", 242 | " \n", 243 | " \n", 244 | " \n", 245 | " \n", 246 | " \n", 247 | " \n", 248 | " \n", 249 | " \n", 250 | " \n", 251 | " \n", 252 | " \n", 253 | " \n", 254 | " \n", 255 | " \n", 256 | " \n", 257 | " \n", 258 | " \n", 259 | " \n", 260 | " \n", 261 | " \n", 262 | " \n", 263 | " \n", 264 | " \n", 265 | " \n", 266 | " \n", 267 | " \n", 268 | " \n", 269 | " \n", 270 | " \n", 271 | " \n", 272 | " \n", 273 | " \n", 274 | " \n", 275 | " \n", 276 | " \n", 277 | " \n", 278 | " \n", 279 | " \n", 280 | " \n", 281 | " \n", 282 | " \n", 283 | " \n", 284 | " \n", 285 | " \n", 286 | " \n", 287 | " \n", 288 | " \n", 289 | " \n", 290 | " \n", 291 | " \n", 292 | " \n", 293 | " \n", 294 | " \n", 295 | " \n", 296 | " \n", 297 | " \n", 298 | " \n", 299 | " \n", 300 | " \n", 301 | " \n", 302 | " \n", 303 | " \n", 304 | " \n", 305 | " \n", 306 | " \n", 307 | " \n", 308 | " \n", 309 | " \n", 310 | " \n", 311 | " \n", 312 | " \n", 313 | " \n", 314 | " \n", 315 | " \n", 316 | " \n", 317 | " \n", 318 | " \n", 319 | " \n", 320 | " \n", 321 | " \n", 322 | " \n", 323 | " \n", 324 | " \n", 325 | " \n", 326 | " \n", 327 | " \n", 328 | " \n", 329 | " \n", 330 | " \n", 331 | " \n", 332 | " \n", 333 | "
classnamefuel_typeaspirationnum_of_doordrive_wheelswheel_baselengthwidthheightcurb_weightfuel_systemcity_mpghighway_mpgprice
12Honda12gasstdfourfwd96.5163.464.054.520101bbl30347295
49Toyota49gasstdtworwd98.4176.265.653.02975mpfi243017669
54Volvo54gasstdfourrwd104.3188.867.256.22912mpfi232812940
25Mitsubishi25gasstdfourfwd96.3172.465.451.623652bbl25326989
11Honda11gasstdtwofwd86.6144.663.950.817131bbl49546479
\n", 334 | "
" 335 | ], 336 | "text/plain": [ 337 | " classname fuel_type aspiration num_of_door drive_wheels wheel_base \\\n", 338 | "12 Honda12 gas std four fwd 96.5 \n", 339 | "49 Toyota49 gas std two rwd 98.4 \n", 340 | "54 Volvo54 gas std four rwd 104.3 \n", 341 | "25 Mitsubishi25 gas std four fwd 96.3 \n", 342 | "11 Honda11 gas std two fwd 86.6 \n", 343 | "\n", 344 | " length width height curb_weight fuel_system city_mpg highway_mpg price \n", 345 | "12 163.4 64.0 54.5 2010 1bbl 30 34 7295 \n", 346 | "49 176.2 65.6 53.0 2975 mpfi 24 30 17669 \n", 347 | "54 188.8 67.2 56.2 2912 mpfi 23 28 12940 \n", 348 | "25 172.4 65.4 51.6 2365 2bbl 25 32 6989 \n", 349 | "11 144.6 63.9 50.8 1713 1bbl 49 54 6479 " 350 | ] 351 | }, 352 | "execution_count": 18, 353 | "metadata": {}, 354 | "output_type": "execute_result" 355 | } 356 | ], 357 | "source": [ 358 | "auto_specs.sample(5)" 359 | ] 360 | }, 361 | { 362 | "cell_type": "code", 363 | "execution_count": 20, 364 | "id": "6f9f40f2", 365 | "metadata": {}, 366 | "outputs": [ 367 | { 368 | "data": { 369 | "text/plain": [ 370 | "(56, 10)" 371 | ] 372 | }, 373 | "execution_count": 20, 374 | "metadata": {}, 375 | "output_type": "execute_result" 376 | } 377 | ], 378 | "source": [ 379 | "auto_features.shape" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": 19, 385 | "id": "3a74d0f2", 386 | "metadata": {}, 387 | "outputs": [ 388 | { 389 | "data": { 390 | "text/html": [ 391 | "
\n", 392 | "\n", 405 | "\n", 406 | " \n", 407 | " \n", 408 | " \n", 409 | " \n", 410 | " \n", 411 | " \n", 412 | " \n", 413 | " \n", 414 | " \n", 415 | " \n", 416 | " \n", 417 | " \n", 418 | " \n", 419 | " \n", 420 | " \n", 421 | " \n", 422 | " \n", 423 | " \n", 424 | " \n", 425 | " \n", 426 | " \n", 427 | " \n", 428 | " \n", 429 | " \n", 430 | " \n", 431 | " \n", 432 | " \n", 433 | " \n", 434 | " \n", 435 | " \n", 436 | " \n", 437 | " \n", 438 | " \n", 439 | " \n", 440 | " \n", 441 | " \n", 442 | " \n", 443 | " \n", 444 | " \n", 445 | " \n", 446 | " \n", 447 | " \n", 448 | " \n", 449 | " \n", 450 | " \n", 451 | " \n", 452 | " \n", 453 | " \n", 454 | " \n", 455 | " \n", 456 | " \n", 457 | " \n", 458 | " \n", 459 | " \n", 460 | " \n", 461 | " \n", 462 | " \n", 463 | " \n", 464 | " \n", 465 | " \n", 466 | " \n", 467 | " \n", 468 | " \n", 469 | " \n", 470 | " \n", 471 | " \n", 472 | " \n", 473 | " \n", 474 | " \n", 475 | " \n", 476 | " \n", 477 | " \n", 478 | " \n", 479 | " \n", 480 | " \n", 481 | " \n", 482 | " \n", 483 | " \n", 484 | " \n", 485 | " \n", 486 | " \n", 487 | " \n", 488 | "
classnameengine_locationengine_typenum_of_cylindersengine_sizeborestrokecompression_ratiohorse_powerpeak_rpm
13Wagon13frontohcfour922.923.419.2766000
9Sedan9frontohcfour902.973.239.4685500
16Sedan16frontdohcsix2583.634.178.11764750
5Sedan5frontohcfour1083.52.88.81015800
18Sedan18frontohcfour913.033.159.0685000
\n", 489 | "
" 490 | ], 491 | "text/plain": [ 492 | " classname engine_location engine_type num_of_cylinders engine_size bore \\\n", 493 | "13 Wagon13 front ohc four 92 2.92 \n", 494 | "9 Sedan9 front ohc four 90 2.97 \n", 495 | "16 Sedan16 front dohc six 258 3.63 \n", 496 | "5 Sedan5 front ohc four 108 3.5 \n", 497 | "18 Sedan18 front ohc four 91 3.03 \n", 498 | "\n", 499 | " stroke compression_ratio horse_power peak_rpm \n", 500 | "13 3.41 9.2 76 6000 \n", 501 | "9 3.23 9.4 68 5500 \n", 502 | "16 4.17 8.1 176 4750 \n", 503 | "5 2.8 8.8 101 5800 \n", 504 | "18 3.15 9.0 68 5000 " 505 | ] 506 | }, 507 | "execution_count": 19, 508 | "metadata": {}, 509 | "output_type": "execute_result" 510 | } 511 | ], 512 | "source": [ 513 | "auto_features.sample(5)" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": 20, 519 | "id": "e6082ad4", 520 | "metadata": {}, 521 | "outputs": [], 522 | "source": [ 523 | "from codegenerator import CodeGenerator " 524 | ] 525 | }, 526 | { 527 | "cell_type": "code", 528 | "execution_count": 21, 529 | "id": "8cc4eadc", 530 | "metadata": {}, 531 | "outputs": [], 532 | "source": [ 533 | "codegen = CodeGenerator()" 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": 22, 539 | "id": "c3e5e025", 540 | "metadata": {}, 541 | "outputs": [], 542 | "source": [ 543 | "def generatelib():\n", 544 | " codegen.generate_meta()\n", 545 | " codegen.generate_car_catalogue()\n", 546 | " codegen.generate_carmake_code()\n", 547 | " codegen.generate_bodystyle_parent()\n", 548 | " codegen.generate_salestype_code()\n", 549 | " codegen.generate_newsale_code()\n", 550 | " codegen.generate_resale_code()\n", 551 | " for index, row in auto_specs.iterrows():\n", 552 | " carspecs = dict(row)\n", 553 | " classname = carspecs['classname']\n", 554 | " del carspecs['classname']\n", 555 | " codegen.generate_car_code(classname = classname, carspecs = carspecs)\n", 556 | "\n", 557 | " for index, row in auto_features.iterrows():\n", 558 | " carfeatures = dict(row)\n", 559 | " classname = carfeatures['classname']\n", 560 | " del carfeatures['classname']\n", 561 | " codegen.generate_bodystyle_code(classname = classname, carfeatures = carfeatures)" 562 | ] 563 | }, 564 | { 565 | "cell_type": "code", 566 | "execution_count": 23, 567 | "id": "da320cf9", 568 | "metadata": {}, 569 | "outputs": [], 570 | "source": [ 571 | "from contextlib import redirect_stdout\n", 572 | "with open('abccaragencylib.py', 'w') as code:\n", 573 | " with redirect_stdout(code):\n", 574 | " generatelib()\n", 575 | "code.close()" 576 | ] 577 | }, 578 | { 579 | "cell_type": "code", 580 | "execution_count": null, 581 | "id": "d94e3490", 582 | "metadata": {}, 583 | "outputs": [], 584 | "source": [] 585 | } 586 | ], 587 | "metadata": { 588 | "kernelspec": { 589 | "display_name": "Python 3", 590 | "language": "python", 591 | "name": "python3" 592 | }, 593 | "language_info": { 594 | "codemirror_mode": { 595 | "name": "ipython", 596 | "version": 3 597 | }, 598 | "file_extension": ".py", 599 | "mimetype": "text/x-python", 600 | "name": "python", 601 | "nbconvert_exporter": "python", 602 | "pygments_lexer": "ipython3", 603 | "version": "3.9.5" 604 | } 605 | }, 606 | "nbformat": 4, 607 | "nbformat_minor": 5 608 | } 609 | -------------------------------------------------------------------------------- /Chapter12/chapter 12.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "bb8997e4", 6 | "metadata": {}, 7 | "source": [ 8 | "## Chapter 12" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "f8d42047", 14 | "metadata": {}, 15 | "source": [ 16 | "### Chain of responsibility" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 1, 22 | "id": "2cde1e09", 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "class InvoiceHandler(object):\n", 27 | " def __init__(self):\n", 28 | " self.next_action = None\n", 29 | " \n", 30 | " def handle(self,print_invoice):\n", 31 | " self.next_action.handle(print_invoice)\n", 32 | "\n", 33 | "class InputState(object):\n", 34 | " state_ny = ['NYC','NY','New York','new york']\n", 35 | " state_ca = ['CA', 'California', 'california']\n", 36 | " \n", 37 | "class print_invoice(object):\n", 38 | " def __init__(self,state):\n", 39 | " self.state = state\n", 40 | " self.header = 'State specific Sales tax is applicable for the state of ' + self.state\n", 41 | "\n", 42 | "class NYCHandler(InvoiceHandler):\n", 43 | " def generate_invoice(self, header, state):\n", 44 | " product = 'WashingMachine'\n", 45 | " pricebeforetax = 450 + (450 * 0.19)\n", 46 | " tax_rate = 0.4\n", 47 | " local_rate = 0.055\n", 48 | " tax = pricebeforetax * (tax_rate + local_rate)\n", 49 | " finalsellingprice = pricebeforetax + tax\n", 50 | " print('**************ABC Megamart*****************')\n", 51 | " print('***********------------------**************')\n", 52 | " print(header)\n", 53 | " print('Product: ', product)\n", 54 | " print('Tax: ', tax)\n", 55 | " print('Total Price: ', finalsellingprice)\n", 56 | " print('***********------------------**************') \n", 57 | " \n", 58 | " def handle(self,print_invoice):\n", 59 | " if print_invoice.state in InputState.state_ny:\n", 60 | " self.generate_invoice(print_invoice.header, print_invoice.state)\n", 61 | " \n", 62 | " else:\n", 63 | " super(NYCHandler, self).handle(print_invoice)\n", 64 | " \n", 65 | "class CAHandler(InvoiceHandler):\n", 66 | " def generate_invoice(self, header, state):\n", 67 | " product = 'WashingMachine'\n", 68 | " pricebeforetax = 480 + (480 * 0.14)\n", 69 | " tax_rate = 0.35\n", 70 | " local_rate = 0.077\n", 71 | " tax = pricebeforetax * (tax_rate + local_rate)\n", 72 | " finalsellingprice = pricebeforetax + tax\n", 73 | " print('**************ABC Megamart*****************')\n", 74 | " print('***********------------------**************')\n", 75 | " print(header)\n", 76 | " print('Product: ', product)\n", 77 | " print('Tax: ', tax)\n", 78 | " print('Total Price: ', finalsellingprice)\n", 79 | " print('***********------------------**************') \n", 80 | " \n", 81 | " def handle(self,print_invoice):\n", 82 | " if print_invoice.state in InputState.state_ca:\n", 83 | " self.generate_invoice(print_invoice.header, print_invoice.state)\n", 84 | " \n", 85 | " else:\n", 86 | " super(CAHandler, self).handle(print_invoice)\n", 87 | "\n", 88 | "class ExceptionHandler(InvoiceHandler):\n", 89 | " def handle(self,print_invoice):\n", 90 | " print(\"No branches in the state\") \n", 91 | " " 92 | ] 93 | }, 94 | { 95 | "cell_type": "code", 96 | "execution_count": 2, 97 | "id": "1c037c76", 98 | "metadata": {}, 99 | "outputs": [], 100 | "source": [ 101 | "def invoice_requestor(state):\n", 102 | " invoice = print_invoice(state)\n", 103 | " nychandler = NYCHandler()\n", 104 | " cahandler = CAHandler()\n", 105 | "\n", 106 | " nychandler.next_action = cahandler\n", 107 | " cahandler.next_action = ExceptionHandler()\n", 108 | " nychandler.handle(invoice)" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": 3, 114 | "id": "9b32491c", 115 | "metadata": {}, 116 | "outputs": [ 117 | { 118 | "name": "stdout", 119 | "output_type": "stream", 120 | "text": [ 121 | "**************ABC Megamart*****************\n", 122 | "***********------------------**************\n", 123 | "State specific Sales tax is applicable for the state of CA\n", 124 | "Product: WashingMachine\n", 125 | "Tax: 233.6544\n", 126 | "Total Price: 780.8544\n", 127 | "***********------------------**************\n" 128 | ] 129 | } 130 | ], 131 | "source": [ 132 | "invoice_requestor('CA')" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": 4, 138 | "id": "2680e1f7", 139 | "metadata": {}, 140 | "outputs": [ 141 | { 142 | "name": "stdout", 143 | "output_type": "stream", 144 | "text": [ 145 | "**************ABC Megamart*****************\n", 146 | "***********------------------**************\n", 147 | "State specific Sales tax is applicable for the state of NYC\n", 148 | "Product: WashingMachine\n", 149 | "Tax: 243.6525\n", 150 | "Total Price: 779.1525\n", 151 | "***********------------------**************\n" 152 | ] 153 | } 154 | ], 155 | "source": [ 156 | "invoice_requestor('NYC')" 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": 5, 162 | "id": "93c4c14d", 163 | "metadata": {}, 164 | "outputs": [ 165 | { 166 | "name": "stdout", 167 | "output_type": "stream", 168 | "text": [ 169 | "No branches in the state\n" 170 | ] 171 | } 172 | ], 173 | "source": [ 174 | "invoice_requestor('TEXAS')" 175 | ] 176 | }, 177 | { 178 | "cell_type": "markdown", 179 | "id": "96ada154", 180 | "metadata": {}, 181 | "source": [ 182 | "### Command" 183 | ] 184 | }, 185 | { 186 | "cell_type": "code", 187 | "execution_count": 6, 188 | "id": "c9c1e3a0", 189 | "metadata": {}, 190 | "outputs": [], 191 | "source": [ 192 | "from abc import ABC, abstractmethod\n", 193 | "\n", 194 | "class Billing:\n", 195 | " sales = {'purchase_price': 450,\n", 196 | " 'profit_margin': 0.19,\n", 197 | " 'tax_rate': 0.4,\n", 198 | " 'discount_rate': 0.10\n", 199 | " } \n", 200 | "\n", 201 | " @abstractmethod\n", 202 | " def apply_discount(self):\n", 203 | " pass\n", 204 | " \n", 205 | " @abstractmethod\n", 206 | " def remove_discount(self):\n", 207 | " pass" 208 | ] 209 | }, 210 | { 211 | "cell_type": "code", 212 | "execution_count": 7, 213 | "id": "d06ffc63", 214 | "metadata": {}, 215 | "outputs": [], 216 | "source": [ 217 | "class DiscountedBilling(Billing):\n", 218 | "\n", 219 | " def apply_discount(self):\n", 220 | " sales = self.sales\n", 221 | " pricebeforetax = sales['purchase_price'] + sales['purchase_price'] * sales['profit_margin']\n", 222 | " finalsellingprice = pricebeforetax + (pricebeforetax * sales['tax_rate'])\n", 223 | " sales['sellingPrice'] = finalsellingprice\n", 224 | " discountedPrice = sales['sellingPrice'] * (1 - sales['discount_rate'])\n", 225 | " return discountedPrice" 226 | ] 227 | }, 228 | { 229 | "cell_type": "code", 230 | "execution_count": 8, 231 | "id": "210dd84d", 232 | "metadata": {}, 233 | "outputs": [], 234 | "source": [ 235 | "class ActualBilling(Billing):\n", 236 | "\n", 237 | " def remove_discount(self):\n", 238 | " sales = self.sales\n", 239 | " pricebeforetax = sales['purchase_price'] + sales['purchase_price'] * sales['profit_margin']\n", 240 | " actualprice = pricebeforetax + (pricebeforetax * sales['tax_rate'])\n", 241 | " return actualprice" 242 | ] 243 | }, 244 | { 245 | "cell_type": "code", 246 | "execution_count": 9, 247 | "id": "a000b8a8", 248 | "metadata": {}, 249 | "outputs": [], 250 | "source": [ 251 | "class ExecuteBilling:\n", 252 | " @abstractmethod\n", 253 | " def exec_discount(self):\n", 254 | " pass\n", 255 | "\n", 256 | " @abstractmethod\n", 257 | " def revoke_discount(self):\n", 258 | " pass" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": 10, 264 | "id": "00052d06", 265 | "metadata": {}, 266 | "outputs": [], 267 | "source": [ 268 | "class ExecuteDiscountedBilling(ExecuteBilling):\n", 269 | " def __init__(self, instance):\n", 270 | " self.instance = instance\n", 271 | " \n", 272 | " def exec_discount(self):\n", 273 | " print('Discount applied...')\n", 274 | " return self.instance.apply_discount()\n", 275 | " \n", 276 | " def revoke_discount(self, revokeInstance):\n", 277 | " revokeInstance.reset(ExecuteActualBilling(ActualBilling()))\n", 278 | " return revokeInstance.runcalc()" 279 | ] 280 | }, 281 | { 282 | "cell_type": "code", 283 | "execution_count": 11, 284 | "id": "5e026acf", 285 | "metadata": {}, 286 | "outputs": [], 287 | "source": [ 288 | "class ExecuteActualBilling(ExecuteBilling):\n", 289 | " def __init__(self, instance):\n", 290 | " self.instance = instance\n", 291 | " \n", 292 | " def exec_discount(self):\n", 293 | " print('Discount removed...')\n", 294 | " return self.instance.remove_discount()\n", 295 | " \n", 296 | " def revoke_discount(self, revokeInstance):\n", 297 | " revokeInstance.reset(ExecuteDiscountedBilling(DiscountedBilling()))\n", 298 | " return revokeInstance.runcalc()" 299 | ] 300 | }, 301 | { 302 | "cell_type": "code", 303 | "execution_count": 12, 304 | "id": "ac9f530b", 305 | "metadata": {}, 306 | "outputs": [], 307 | "source": [ 308 | "class RequestAction:\n", 309 | " def __init__(self, action):\n", 310 | " self.action = action\n", 311 | "\n", 312 | " def reset(self, action):\n", 313 | " print(\"Resetting command...\")\n", 314 | " self.action = action\n", 315 | "\n", 316 | " def runcalc(self):\n", 317 | " return self.action.exec_discount()\n", 318 | " \n", 319 | " def revert(self):\n", 320 | " print(\"Reverting the previous action...\")\n", 321 | " return self.action.revoke_discount(self)" 322 | ] 323 | }, 324 | { 325 | "cell_type": "code", 326 | "execution_count": 13, 327 | "id": "4127bf0d", 328 | "metadata": {}, 329 | "outputs": [], 330 | "source": [ 331 | "class Tester:\n", 332 | " def __init__(self):\n", 333 | " billing = Billing()\n", 334 | "\n", 335 | " discount = ExecuteDiscountedBilling(DiscountedBilling())\n", 336 | " actual = ExecuteActualBilling(ActualBilling())\n", 337 | " requestor = RequestAction(discount) \n", 338 | "\n", 339 | " print(requestor.runcalc())\n", 340 | "\n", 341 | " requestor.reset(actual)\n", 342 | "\n", 343 | " print(requestor.runcalc())\n", 344 | "\n", 345 | " print(requestor.revert())\n", 346 | "\n", 347 | " print(requestor.revert()) " 348 | ] 349 | }, 350 | { 351 | "cell_type": "code", 352 | "execution_count": 14, 353 | "id": "60b76f51", 354 | "metadata": {}, 355 | "outputs": [ 356 | { 357 | "name": "stdout", 358 | "output_type": "stream", 359 | "text": [ 360 | "Discount applied...\n", 361 | "674.73\n", 362 | "Resetting command...\n", 363 | "Discount removed...\n", 364 | "749.7\n", 365 | "Reverting the previous action...\n", 366 | "Resetting command...\n", 367 | "Discount applied...\n", 368 | "674.73\n", 369 | "Reverting the previous action...\n", 370 | "Resetting command...\n", 371 | "Discount removed...\n", 372 | "749.7\n" 373 | ] 374 | }, 375 | { 376 | "data": { 377 | "text/plain": [ 378 | "<__main__.Tester at 0x1d8d0cf56d0>" 379 | ] 380 | }, 381 | "execution_count": 14, 382 | "metadata": {}, 383 | "output_type": "execute_result" 384 | } 385 | ], 386 | "source": [ 387 | "Tester()" 388 | ] 389 | }, 390 | { 391 | "cell_type": "markdown", 392 | "id": "a4e7d3f7", 393 | "metadata": {}, 394 | "source": [ 395 | "### Strategy pattern" 396 | ] 397 | }, 398 | { 399 | "cell_type": "code", 400 | "execution_count": 15, 401 | "id": "7727b8d3", 402 | "metadata": {}, 403 | "outputs": [], 404 | "source": [ 405 | "class SuperMarket():\n", 406 | " \n", 407 | " def __init__(self,STRATEGY, items, name, scan, units, tax, itemtype = None):\n", 408 | " self.STRATEGY = STRATEGY\n", 409 | " self.items = items\n", 410 | " self.name = name\n", 411 | " self.scan = scan\n", 412 | " self.units = units\n", 413 | " self.tax = tax\n", 414 | " self.itemtype = itemtype\n", 415 | " \n", 416 | " def return_cart(self):\n", 417 | " cartItems = []\n", 418 | " for i in self.items:\n", 419 | " cartItems.append(i)\n", 420 | " return cartItems\n", 421 | " \n", 422 | " def goto_counter(self):\n", 423 | " countername = self.name\n", 424 | " return countername\n", 425 | "\n", 426 | " def scan_bar_code(self):\n", 427 | " codes = []\n", 428 | " for i in self.scan:\n", 429 | " codes.append(i)\n", 430 | " return codes\n", 431 | " \n", 432 | " def add_billing(self):\n", 433 | " self.codes = self.scan_bar_code()\n", 434 | " pricetag = []\n", 435 | " for i in self.units:\n", 436 | " pricetag.append(i)\n", 437 | " bill = dict(zip(self.codes, pricetag))\n", 438 | " return bill\n", 439 | " \n", 440 | " def add_tax(self):\n", 441 | " taxed = []\n", 442 | " for i in self.tax:\n", 443 | " taxed.append(i)\n", 444 | " return taxed\n", 445 | " \n", 446 | " def calc_bill(self):\n", 447 | " bill = self.add_billing()\n", 448 | " items = []\n", 449 | " cartItems = self.return_cart()\n", 450 | " calc_bill = []\n", 451 | " taxes = self.add_tax()\n", 452 | " for item,tax in zip(bill.items(),taxes):\n", 453 | " items.append(item[1])\n", 454 | " calc_bill.append(item[1] + item[1]*tax)\n", 455 | " finalbill = dict(zip(cartItems, calc_bill))\n", 456 | " return finalbill\n", 457 | " \n", 458 | " def print_invoice(self):\n", 459 | " finalbill = self.calc_bill()\n", 460 | " final_total = sum(finalbill.values())\n", 461 | " print('**************ABC Megamart*****************')\n", 462 | " print('***********------------------**************')\n", 463 | " print('Counter Name: ', self.goto_counter())\n", 464 | " for item,price in finalbill.items():\n", 465 | " print(item,\": \", price)\n", 466 | " print('Total:',final_total)\n", 467 | " print('***********------------------**************')\n", 468 | " print('***************PAID************************')\n", 469 | " \n", 470 | " def pipeline_template(self):\n", 471 | " self.return_cart()\n", 472 | " self.goto_counter()\n", 473 | " self.STRATEGY.redirect_counter()\n", 474 | " self.scan_bar_code()\n", 475 | " self.add_billing()\n", 476 | " self.add_tax()\n", 477 | " self.calc_bill()\n", 478 | " self.print_invoice()" 479 | ] 480 | }, 481 | { 482 | "cell_type": "code", 483 | "execution_count": 16, 484 | "id": "f0cca36b", 485 | "metadata": {}, 486 | "outputs": [], 487 | "source": [ 488 | "class VegeCounter():\n", 489 | " def redirect_counter():\n", 490 | " print(\"**************Move to Vege Counter**************\")" 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "execution_count": 17, 496 | "id": "c7a2c5fd", 497 | "metadata": {}, 498 | "outputs": [], 499 | "source": [ 500 | "class ElectronicsCounter():\n", 501 | " def redirect_counter():\n", 502 | " print(\"**************Move to Electronics Counter**************\")" 503 | ] 504 | }, 505 | { 506 | "cell_type": "code", 507 | "execution_count": 18, 508 | "id": "a9314900", 509 | "metadata": {}, 510 | "outputs": [], 511 | "source": [ 512 | "def run_pipeline(domain = SuperMarket):\n", 513 | " domain.pipeline_template()" 514 | ] 515 | }, 516 | { 517 | "cell_type": "code", 518 | "execution_count": 19, 519 | "id": "1a0b4d12", 520 | "metadata": {}, 521 | "outputs": [ 522 | { 523 | "name": "stdout", 524 | "output_type": "stream", 525 | "text": [ 526 | "**************Move to Vege Counter**************\n", 527 | "**************ABC Megamart*****************\n", 528 | "***********------------------**************\n", 529 | "Counter Name: ['Vegetable Counter']\n", 530 | "Onions : 10.4\n", 531 | "Tomatoes : 15.45\n", 532 | "Cabbage : 12.42\n", 533 | "Beetroot : 14.35\n", 534 | "Total: 52.620000000000005\n", 535 | "***********------------------**************\n", 536 | "***************PAID************************\n" 537 | ] 538 | } 539 | ], 540 | "source": [ 541 | "run_pipeline(SuperMarket(STRATEGY = VegeCounter,\n", 542 | " items = ['Onions','Tomatoes','Cabbage','Beetroot'],\n", 543 | " name = ['Vegetable Counter'],\n", 544 | " scan = [113323,3434332,2131243,2332783],\n", 545 | " units = [10,15,12,14],\n", 546 | " tax = [0.04,0.03,0.035,0.025],\n", 547 | " itemtype = ['Vegetables'],\n", 548 | " ))" 549 | ] 550 | }, 551 | { 552 | "cell_type": "code", 553 | "execution_count": 20, 554 | "id": "0246cee0", 555 | "metadata": {}, 556 | "outputs": [ 557 | { 558 | "name": "stdout", 559 | "output_type": "stream", 560 | "text": [ 561 | "**************Move to Electronics Counter**************\n", 562 | "**************ABC Megamart*****************\n", 563 | "***********------------------**************\n", 564 | "Counter Name: ['Electronics Counter']\n", 565 | "television : 104.0\n", 566 | "keyboard : 16.48\n", 567 | "mouse : 14.49\n", 568 | "Total: 134.97\n", 569 | "***********------------------**************\n", 570 | "***************PAID************************\n" 571 | ] 572 | } 573 | ], 574 | "source": [ 575 | "run_pipeline(SuperMarket(STRATEGY = ElectronicsCounter,\n", 576 | " items = ['television','keyboard','mouse'],\n", 577 | " name = ['Electronics Counter'],\n", 578 | " scan = [113323,3434332,2131243],\n", 579 | " units = [100,16,14],\n", 580 | " tax = [0.04,0.03,0.035],\n", 581 | " itemtype = ['Electronics'],\n", 582 | " ))" 583 | ] 584 | }, 585 | { 586 | "cell_type": "markdown", 587 | "id": "55409b79", 588 | "metadata": {}, 589 | "source": [ 590 | "### These are all the examples covered in this chapter." 591 | ] 592 | } 593 | ], 594 | "metadata": { 595 | "kernelspec": { 596 | "display_name": "Python 3", 597 | "language": "python", 598 | "name": "python3" 599 | }, 600 | "language_info": { 601 | "codemirror_mode": { 602 | "name": "ipython", 603 | "version": 3 604 | }, 605 | "file_extension": ".py", 606 | "mimetype": "text/x-python", 607 | "name": "python", 608 | "nbconvert_exporter": "python", 609 | "pygments_lexer": "ipython3", 610 | "version": "3.9.5" 611 | } 612 | }, 613 | "nbformat": 4, 614 | "nbformat_minor": 5 615 | } 616 | -------------------------------------------------------------------------------- /Chapter15/automobile.csv: -------------------------------------------------------------------------------- 1 | symboling,normalized-losses,make,fuel-type,aspiration,num-of-doors,body-style,drive-wheels,engine-location,wheel-base,length,width,height,curb-weight,engine-type,num-of-cylinders,engine-size,fuel-system,bore,stroke,compression-ratio,horsepower,peak-rpm,city-mpg,highway-mpg,price 2 | 3,?,alfa-romero,gas,std,two,convertible,rwd,front,88.6,168.8,64.1,48.8,2548,dohc,four,130,mpfi,3.47,2.68,9,111,5000,21,27,13495 3 | 3,?,alfa-romero,gas,std,two,convertible,rwd,front,88.6,168.8,64.1,48.8,2548,dohc,four,130,mpfi,3.47,2.68,9,111,5000,21,27,16500 4 | 1,?,alfa-romero,gas,std,two,hatchback,rwd,front,94.5,171.2,65.5,52.4,2823,ohcv,six,152,mpfi,2.68,3.47,9,154,5000,19,26,16500 5 | 2,164,audi,gas,std,four,sedan,fwd,front,99.8,176.6,66.2,54.3,2337,ohc,four,109,mpfi,3.19,3.4,10,102,5500,24,30,13950 6 | 2,164,audi,gas,std,four,sedan,4wd,front,99.4,176.6,66.4,54.3,2824,ohc,five,136,mpfi,3.19,3.4,8,115,5500,18,22,17450 7 | 2,?,audi,gas,std,two,sedan,fwd,front,99.8,177.3,66.3,53.1,2507,ohc,five,136,mpfi,3.19,3.4,8.5,110,5500,19,25,15250 8 | 1,158,audi,gas,std,four,sedan,fwd,front,105.8,192.7,71.4,55.7,2844,ohc,five,136,mpfi,3.19,3.4,8.5,110,5500,19,25,17710 9 | 1,?,audi,gas,std,four,wagon,fwd,front,105.8,192.7,71.4,55.7,2954,ohc,five,136,mpfi,3.19,3.4,8.5,110,5500,19,25,18920 10 | 1,158,audi,gas,turbo,four,sedan,fwd,front,105.8,192.7,71.4,55.9,3086,ohc,five,131,mpfi,3.13,3.4,8.3,140,5500,17,20,23875 11 | 0,?,audi,gas,turbo,two,hatchback,4wd,front,99.5,178.2,67.9,52,3053,ohc,five,131,mpfi,3.13,3.4,7,160,5500,16,22,? 12 | 2,192,bmw,gas,std,two,sedan,rwd,front,101.2,176.8,64.8,54.3,2395,ohc,four,108,mpfi,3.5,2.8,8.8,101,5800,23,29,16430 13 | 0,192,bmw,gas,std,four,sedan,rwd,front,101.2,176.8,64.8,54.3,2395,ohc,four,108,mpfi,3.5,2.8,8.8,101,5800,23,29,16925 14 | 0,188,bmw,gas,std,two,sedan,rwd,front,101.2,176.8,64.8,54.3,2710,ohc,six,164,mpfi,3.31,3.19,9,121,4250,21,28,20970 15 | 0,188,bmw,gas,std,four,sedan,rwd,front,101.2,176.8,64.8,54.3,2765,ohc,six,164,mpfi,3.31,3.19,9,121,4250,21,28,21105 16 | 1,?,bmw,gas,std,four,sedan,rwd,front,103.5,189,66.9,55.7,3055,ohc,six,164,mpfi,3.31,3.19,9,121,4250,20,25,24565 17 | 0,?,bmw,gas,std,four,sedan,rwd,front,103.5,189,66.9,55.7,3230,ohc,six,209,mpfi,3.62,3.39,8,182,5400,16,22,30760 18 | 0,?,bmw,gas,std,two,sedan,rwd,front,103.5,193.8,67.9,53.7,3380,ohc,six,209,mpfi,3.62,3.39,8,182,5400,16,22,41315 19 | 0,?,bmw,gas,std,four,sedan,rwd,front,110,197,70.9,56.3,3505,ohc,six,209,mpfi,3.62,3.39,8,182,5400,15,20,36880 20 | 2,121,chevrolet,gas,std,two,hatchback,fwd,front,88.4,141.1,60.3,53.2,1488,l,three,61,2bbl,2.91,3.03,9.5,48,5100,47,53,5151 21 | 1,98,chevrolet,gas,std,two,hatchback,fwd,front,94.5,155.9,63.6,52,1874,ohc,four,90,2bbl,3.03,3.11,9.6,70,5400,38,43,6295 22 | 0,81,chevrolet,gas,std,four,sedan,fwd,front,94.5,158.8,63.6,52,1909,ohc,four,90,2bbl,3.03,3.11,9.6,70,5400,38,43,6575 23 | 1,118,dodge,gas,std,two,hatchback,fwd,front,93.7,157.3,63.8,50.8,1876,ohc,four,90,2bbl,2.97,3.23,9.41,68,5500,37,41,5572 24 | 1,118,dodge,gas,std,two,hatchback,fwd,front,93.7,157.3,63.8,50.8,1876,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,31,38,6377 25 | 1,118,dodge,gas,turbo,two,hatchback,fwd,front,93.7,157.3,63.8,50.8,2128,ohc,four,98,mpfi,3.03,3.39,7.6,102,5500,24,30,7957 26 | 1,148,dodge,gas,std,four,hatchback,fwd,front,93.7,157.3,63.8,50.6,1967,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,31,38,6229 27 | 1,148,dodge,gas,std,four,sedan,fwd,front,93.7,157.3,63.8,50.6,1989,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,31,38,6692 28 | 1,148,dodge,gas,std,four,sedan,fwd,front,93.7,157.3,63.8,50.6,1989,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,31,38,7609 29 | 1,148,dodge,gas,turbo,?,sedan,fwd,front,93.7,157.3,63.8,50.6,2191,ohc,four,98,mpfi,3.03,3.39,7.6,102,5500,24,30,8558 30 | -1,110,dodge,gas,std,four,wagon,fwd,front,103.3,174.6,64.6,59.8,2535,ohc,four,122,2bbl,3.34,3.46,8.5,88,5000,24,30,8921 31 | 3,145,dodge,gas,turbo,two,hatchback,fwd,front,95.9,173.2,66.3,50.2,2811,ohc,four,156,mfi,3.6,3.9,7,145,5000,19,24,12964 32 | 2,137,honda,gas,std,two,hatchback,fwd,front,86.6,144.6,63.9,50.8,1713,ohc,four,92,1bbl,2.91,3.41,9.6,58,4800,49,54,6479 33 | 2,137,honda,gas,std,two,hatchback,fwd,front,86.6,144.6,63.9,50.8,1819,ohc,four,92,1bbl,2.91,3.41,9.2,76,6000,31,38,6855 34 | 1,101,honda,gas,std,two,hatchback,fwd,front,93.7,150,64,52.6,1837,ohc,four,79,1bbl,2.91,3.07,10.1,60,5500,38,42,5399 35 | 1,101,honda,gas,std,two,hatchback,fwd,front,93.7,150,64,52.6,1940,ohc,four,92,1bbl,2.91,3.41,9.2,76,6000,30,34,6529 36 | 1,101,honda,gas,std,two,hatchback,fwd,front,93.7,150,64,52.6,1956,ohc,four,92,1bbl,2.91,3.41,9.2,76,6000,30,34,7129 37 | 0,110,honda,gas,std,four,sedan,fwd,front,96.5,163.4,64,54.5,2010,ohc,four,92,1bbl,2.91,3.41,9.2,76,6000,30,34,7295 38 | 0,78,honda,gas,std,four,wagon,fwd,front,96.5,157.1,63.9,58.3,2024,ohc,four,92,1bbl,2.92,3.41,9.2,76,6000,30,34,7295 39 | 0,106,honda,gas,std,two,hatchback,fwd,front,96.5,167.5,65.2,53.3,2236,ohc,four,110,1bbl,3.15,3.58,9,86,5800,27,33,7895 40 | 0,106,honda,gas,std,two,hatchback,fwd,front,96.5,167.5,65.2,53.3,2289,ohc,four,110,1bbl,3.15,3.58,9,86,5800,27,33,9095 41 | 0,85,honda,gas,std,four,sedan,fwd,front,96.5,175.4,65.2,54.1,2304,ohc,four,110,1bbl,3.15,3.58,9,86,5800,27,33,8845 42 | 0,85,honda,gas,std,four,sedan,fwd,front,96.5,175.4,62.5,54.1,2372,ohc,four,110,1bbl,3.15,3.58,9,86,5800,27,33,10295 43 | 0,85,honda,gas,std,four,sedan,fwd,front,96.5,175.4,65.2,54.1,2465,ohc,four,110,mpfi,3.15,3.58,9,101,5800,24,28,12945 44 | 1,107,honda,gas,std,two,sedan,fwd,front,96.5,169.1,66,51,2293,ohc,four,110,2bbl,3.15,3.58,9.1,100,5500,25,31,10345 45 | 0,?,isuzu,gas,std,four,sedan,rwd,front,94.3,170.7,61.8,53.5,2337,ohc,four,111,2bbl,3.31,3.23,8.5,78,4800,24,29,6785 46 | 1,?,isuzu,gas,std,two,sedan,fwd,front,94.5,155.9,63.6,52,1874,ohc,four,90,2bbl,3.03,3.11,9.6,70,5400,38,43,? 47 | 0,?,isuzu,gas,std,four,sedan,fwd,front,94.5,155.9,63.6,52,1909,ohc,four,90,2bbl,3.03,3.11,9.6,70,5400,38,43,? 48 | 2,?,isuzu,gas,std,two,hatchback,rwd,front,96,172.6,65.2,51.4,2734,ohc,four,119,spfi,3.43,3.23,9.2,90,5000,24,29,11048 49 | 0,145,jaguar,gas,std,four,sedan,rwd,front,113,199.6,69.6,52.8,4066,dohc,six,258,mpfi,3.63,4.17,8.1,176,4750,15,19,32250 50 | 0,?,jaguar,gas,std,four,sedan,rwd,front,113,199.6,69.6,52.8,4066,dohc,six,258,mpfi,3.63,4.17,8.1,176,4750,15,19,35550 51 | 0,?,jaguar,gas,std,two,sedan,rwd,front,102,191.7,70.6,47.8,3950,ohcv,twelve,326,mpfi,3.54,2.76,11.5,262,5000,13,17,36000 52 | 1,104,mazda,gas,std,two,hatchback,fwd,front,93.1,159.1,64.2,54.1,1890,ohc,four,91,2bbl,3.03,3.15,9,68,5000,30,31,5195 53 | 1,104,mazda,gas,std,two,hatchback,fwd,front,93.1,159.1,64.2,54.1,1900,ohc,four,91,2bbl,3.03,3.15,9,68,5000,31,38,6095 54 | 1,104,mazda,gas,std,two,hatchback,fwd,front,93.1,159.1,64.2,54.1,1905,ohc,four,91,2bbl,3.03,3.15,9,68,5000,31,38,6795 55 | 1,113,mazda,gas,std,four,sedan,fwd,front,93.1,166.8,64.2,54.1,1945,ohc,four,91,2bbl,3.03,3.15,9,68,5000,31,38,6695 56 | 1,113,mazda,gas,std,four,sedan,fwd,front,93.1,166.8,64.2,54.1,1950,ohc,four,91,2bbl,3.08,3.15,9,68,5000,31,38,7395 57 | 3,150,mazda,gas,std,two,hatchback,rwd,front,95.3,169,65.7,49.6,2380,rotor,two,70,4bbl,?,?,9.4,101,6000,17,23,10945 58 | 3,150,mazda,gas,std,two,hatchback,rwd,front,95.3,169,65.7,49.6,2380,rotor,two,70,4bbl,?,?,9.4,101,6000,17,23,11845 59 | 3,150,mazda,gas,std,two,hatchback,rwd,front,95.3,169,65.7,49.6,2385,rotor,two,70,4bbl,?,?,9.4,101,6000,17,23,13645 60 | 3,150,mazda,gas,std,two,hatchback,rwd,front,95.3,169,65.7,49.6,2500,rotor,two,80,mpfi,?,?,9.4,135,6000,16,23,15645 61 | 1,129,mazda,gas,std,two,hatchback,fwd,front,98.8,177.8,66.5,53.7,2385,ohc,four,122,2bbl,3.39,3.39,8.6,84,4800,26,32,8845 62 | 0,115,mazda,gas,std,four,sedan,fwd,front,98.8,177.8,66.5,55.5,2410,ohc,four,122,2bbl,3.39,3.39,8.6,84,4800,26,32,8495 63 | 1,129,mazda,gas,std,two,hatchback,fwd,front,98.8,177.8,66.5,53.7,2385,ohc,four,122,2bbl,3.39,3.39,8.6,84,4800,26,32,10595 64 | 0,115,mazda,gas,std,four,sedan,fwd,front,98.8,177.8,66.5,55.5,2410,ohc,four,122,2bbl,3.39,3.39,8.6,84,4800,26,32,10245 65 | 0,?,mazda,diesel,std,?,sedan,fwd,front,98.8,177.8,66.5,55.5,2443,ohc,four,122,idi,3.39,3.39,22.7,64,4650,36,42,10795 66 | 0,115,mazda,gas,std,four,hatchback,fwd,front,98.8,177.8,66.5,55.5,2425,ohc,four,122,2bbl,3.39,3.39,8.6,84,4800,26,32,11245 67 | 0,118,mazda,gas,std,four,sedan,rwd,front,104.9,175,66.1,54.4,2670,ohc,four,140,mpfi,3.76,3.16,8,120,5000,19,27,18280 68 | 0,?,mazda,diesel,std,four,sedan,rwd,front,104.9,175,66.1,54.4,2700,ohc,four,134,idi,3.43,3.64,22,72,4200,31,39,18344 69 | -1,93,mercedes-benz,diesel,turbo,four,sedan,rwd,front,110,190.9,70.3,56.5,3515,ohc,five,183,idi,3.58,3.64,21.5,123,4350,22,25,25552 70 | -1,93,mercedes-benz,diesel,turbo,four,wagon,rwd,front,110,190.9,70.3,58.7,3750,ohc,five,183,idi,3.58,3.64,21.5,123,4350,22,25,28248 71 | 0,93,mercedes-benz,diesel,turbo,two,hardtop,rwd,front,106.7,187.5,70.3,54.9,3495,ohc,five,183,idi,3.58,3.64,21.5,123,4350,22,25,28176 72 | -1,93,mercedes-benz,diesel,turbo,four,sedan,rwd,front,115.6,202.6,71.7,56.3,3770,ohc,five,183,idi,3.58,3.64,21.5,123,4350,22,25,31600 73 | -1,?,mercedes-benz,gas,std,four,sedan,rwd,front,115.6,202.6,71.7,56.5,3740,ohcv,eight,234,mpfi,3.46,3.1,8.3,155,4750,16,18,34184 74 | 3,142,mercedes-benz,gas,std,two,convertible,rwd,front,96.6,180.3,70.5,50.8,3685,ohcv,eight,234,mpfi,3.46,3.1,8.3,155,4750,16,18,35056 75 | 0,?,mercedes-benz,gas,std,four,sedan,rwd,front,120.9,208.1,71.7,56.7,3900,ohcv,eight,308,mpfi,3.8,3.35,8,184,4500,14,16,40960 76 | 1,?,mercedes-benz,gas,std,two,hardtop,rwd,front,112,199.2,72,55.4,3715,ohcv,eight,304,mpfi,3.8,3.35,8,184,4500,14,16,45400 77 | 1,?,mercury,gas,turbo,two,hatchback,rwd,front,102.7,178.4,68,54.8,2910,ohc,four,140,mpfi,3.78,3.12,8,175,5000,19,24,16503 78 | 2,161,mitsubishi,gas,std,two,hatchback,fwd,front,93.7,157.3,64.4,50.8,1918,ohc,four,92,2bbl,2.97,3.23,9.4,68,5500,37,41,5389 79 | 2,161,mitsubishi,gas,std,two,hatchback,fwd,front,93.7,157.3,64.4,50.8,1944,ohc,four,92,2bbl,2.97,3.23,9.4,68,5500,31,38,6189 80 | 2,161,mitsubishi,gas,std,two,hatchback,fwd,front,93.7,157.3,64.4,50.8,2004,ohc,four,92,2bbl,2.97,3.23,9.4,68,5500,31,38,6669 81 | 1,161,mitsubishi,gas,turbo,two,hatchback,fwd,front,93,157.3,63.8,50.8,2145,ohc,four,98,spdi,3.03,3.39,7.6,102,5500,24,30,7689 82 | 3,153,mitsubishi,gas,turbo,two,hatchback,fwd,front,96.3,173,65.4,49.4,2370,ohc,four,110,spdi,3.17,3.46,7.5,116,5500,23,30,9959 83 | 3,153,mitsubishi,gas,std,two,hatchback,fwd,front,96.3,173,65.4,49.4,2328,ohc,four,122,2bbl,3.35,3.46,8.5,88,5000,25,32,8499 84 | 3,?,mitsubishi,gas,turbo,two,hatchback,fwd,front,95.9,173.2,66.3,50.2,2833,ohc,four,156,spdi,3.58,3.86,7,145,5000,19,24,12629 85 | 3,?,mitsubishi,gas,turbo,two,hatchback,fwd,front,95.9,173.2,66.3,50.2,2921,ohc,four,156,spdi,3.59,3.86,7,145,5000,19,24,14869 86 | 3,?,mitsubishi,gas,turbo,two,hatchback,fwd,front,95.9,173.2,66.3,50.2,2926,ohc,four,156,spdi,3.59,3.86,7,145,5000,19,24,14489 87 | 1,125,mitsubishi,gas,std,four,sedan,fwd,front,96.3,172.4,65.4,51.6,2365,ohc,four,122,2bbl,3.35,3.46,8.5,88,5000,25,32,6989 88 | 1,125,mitsubishi,gas,std,four,sedan,fwd,front,96.3,172.4,65.4,51.6,2405,ohc,four,122,2bbl,3.35,3.46,8.5,88,5000,25,32,8189 89 | 1,125,mitsubishi,gas,turbo,four,sedan,fwd,front,96.3,172.4,65.4,51.6,2403,ohc,four,110,spdi,3.17,3.46,7.5,116,5500,23,30,9279 90 | -1,137,mitsubishi,gas,std,four,sedan,fwd,front,96.3,172.4,65.4,51.6,2403,ohc,four,110,spdi,3.17,3.46,7.5,116,5500,23,30,9279 91 | 1,128,nissan,gas,std,two,sedan,fwd,front,94.5,165.3,63.8,54.5,1889,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,5499 92 | 1,128,nissan,diesel,std,two,sedan,fwd,front,94.5,165.3,63.8,54.5,2017,ohc,four,103,idi,2.99,3.47,21.9,55,4800,45,50,7099 93 | 1,128,nissan,gas,std,two,sedan,fwd,front,94.5,165.3,63.8,54.5,1918,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,6649 94 | 1,122,nissan,gas,std,four,sedan,fwd,front,94.5,165.3,63.8,54.5,1938,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,6849 95 | 1,103,nissan,gas,std,four,wagon,fwd,front,94.5,170.2,63.8,53.5,2024,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,7349 96 | 1,128,nissan,gas,std,two,sedan,fwd,front,94.5,165.3,63.8,54.5,1951,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,7299 97 | 1,128,nissan,gas,std,two,hatchback,fwd,front,94.5,165.6,63.8,53.3,2028,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,7799 98 | 1,122,nissan,gas,std,four,sedan,fwd,front,94.5,165.3,63.8,54.5,1971,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,7499 99 | 1,103,nissan,gas,std,four,wagon,fwd,front,94.5,170.2,63.8,53.5,2037,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,7999 100 | 2,168,nissan,gas,std,two,hardtop,fwd,front,95.1,162.4,63.8,53.3,2008,ohc,four,97,2bbl,3.15,3.29,9.4,69,5200,31,37,8249 101 | 0,106,nissan,gas,std,four,hatchback,fwd,front,97.2,173.4,65.2,54.7,2324,ohc,four,120,2bbl,3.33,3.47,8.5,97,5200,27,34,8949 102 | 0,106,nissan,gas,std,four,sedan,fwd,front,97.2,173.4,65.2,54.7,2302,ohc,four,120,2bbl,3.33,3.47,8.5,97,5200,27,34,9549 103 | 0,128,nissan,gas,std,four,sedan,fwd,front,100.4,181.7,66.5,55.1,3095,ohcv,six,181,mpfi,3.43,3.27,9,152,5200,17,22,13499 104 | 0,108,nissan,gas,std,four,wagon,fwd,front,100.4,184.6,66.5,56.1,3296,ohcv,six,181,mpfi,3.43,3.27,9,152,5200,17,22,14399 105 | 0,108,nissan,gas,std,four,sedan,fwd,front,100.4,184.6,66.5,55.1,3060,ohcv,six,181,mpfi,3.43,3.27,9,152,5200,19,25,13499 106 | 3,194,nissan,gas,std,two,hatchback,rwd,front,91.3,170.7,67.9,49.7,3071,ohcv,six,181,mpfi,3.43,3.27,9,160,5200,19,25,17199 107 | 3,194,nissan,gas,turbo,two,hatchback,rwd,front,91.3,170.7,67.9,49.7,3139,ohcv,six,181,mpfi,3.43,3.27,7.8,200,5200,17,23,19699 108 | 1,231,nissan,gas,std,two,hatchback,rwd,front,99.2,178.5,67.9,49.7,3139,ohcv,six,181,mpfi,3.43,3.27,9,160,5200,19,25,18399 109 | 0,161,peugot,gas,std,four,sedan,rwd,front,107.9,186.7,68.4,56.7,3020,l,four,120,mpfi,3.46,3.19,8.4,97,5000,19,24,11900 110 | 0,161,peugot,diesel,turbo,four,sedan,rwd,front,107.9,186.7,68.4,56.7,3197,l,four,152,idi,3.7,3.52,21,95,4150,28,33,13200 111 | 0,?,peugot,gas,std,four,wagon,rwd,front,114.2,198.9,68.4,58.7,3230,l,four,120,mpfi,3.46,3.19,8.4,97,5000,19,24,12440 112 | 0,?,peugot,diesel,turbo,four,wagon,rwd,front,114.2,198.9,68.4,58.7,3430,l,four,152,idi,3.7,3.52,21,95,4150,25,25,13860 113 | 0,161,peugot,gas,std,four,sedan,rwd,front,107.9,186.7,68.4,56.7,3075,l,four,120,mpfi,3.46,2.19,8.4,95,5000,19,24,15580 114 | 0,161,peugot,diesel,turbo,four,sedan,rwd,front,107.9,186.7,68.4,56.7,3252,l,four,152,idi,3.7,3.52,21,95,4150,28,33,16900 115 | 0,?,peugot,gas,std,four,wagon,rwd,front,114.2,198.9,68.4,56.7,3285,l,four,120,mpfi,3.46,2.19,8.4,95,5000,19,24,16695 116 | 0,?,peugot,diesel,turbo,four,wagon,rwd,front,114.2,198.9,68.4,58.7,3485,l,four,152,idi,3.7,3.52,21,95,4150,25,25,17075 117 | 0,161,peugot,gas,std,four,sedan,rwd,front,107.9,186.7,68.4,56.7,3075,l,four,120,mpfi,3.46,3.19,8.4,97,5000,19,24,16630 118 | 0,161,peugot,diesel,turbo,four,sedan,rwd,front,107.9,186.7,68.4,56.7,3252,l,four,152,idi,3.7,3.52,21,95,4150,28,33,17950 119 | 0,161,peugot,gas,turbo,four,sedan,rwd,front,108,186.7,68.3,56,3130,l,four,134,mpfi,3.61,3.21,7,142,5600,18,24,18150 120 | 1,119,plymouth,gas,std,two,hatchback,fwd,front,93.7,157.3,63.8,50.8,1918,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,37,41,5572 121 | 1,119,plymouth,gas,turbo,two,hatchback,fwd,front,93.7,157.3,63.8,50.8,2128,ohc,four,98,spdi,3.03,3.39,7.6,102,5500,24,30,7957 122 | 1,154,plymouth,gas,std,four,hatchback,fwd,front,93.7,157.3,63.8,50.6,1967,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,31,38,6229 123 | 1,154,plymouth,gas,std,four,sedan,fwd,front,93.7,167.3,63.8,50.8,1989,ohc,four,90,2bbl,2.97,3.23,9.4,68,5500,31,38,6692 124 | 1,154,plymouth,gas,std,four,sedan,fwd,front,93.7,167.3,63.8,50.8,2191,ohc,four,98,2bbl,2.97,3.23,9.4,68,5500,31,38,7609 125 | -1,74,plymouth,gas,std,four,wagon,fwd,front,103.3,174.6,64.6,59.8,2535,ohc,four,122,2bbl,3.35,3.46,8.5,88,5000,24,30,8921 126 | 3,?,plymouth,gas,turbo,two,hatchback,rwd,front,95.9,173.2,66.3,50.2,2818,ohc,four,156,spdi,3.59,3.86,7,145,5000,19,24,12764 127 | 3,186,porsche,gas,std,two,hatchback,rwd,front,94.5,168.9,68.3,50.2,2778,ohc,four,151,mpfi,3.94,3.11,9.5,143,5500,19,27,22018 128 | 3,?,porsche,gas,std,two,hardtop,rwd,rear,89.5,168.9,65,51.6,2756,ohcf,six,194,mpfi,3.74,2.9,9.5,207,5900,17,25,32528 129 | 3,?,porsche,gas,std,two,hardtop,rwd,rear,89.5,168.9,65,51.6,2756,ohcf,six,194,mpfi,3.74,2.9,9.5,207,5900,17,25,34028 130 | 3,?,porsche,gas,std,two,convertible,rwd,rear,89.5,168.9,65,51.6,2800,ohcf,six,194,mpfi,3.74,2.9,9.5,207,5900,17,25,37028 131 | 1,?,porsche,gas,std,two,hatchback,rwd,front,98.4,175.7,72.3,50.5,3366,dohcv,eight,203,mpfi,3.94,3.11,10,288,5750,17,28,? 132 | 0,?,renault,gas,std,four,wagon,fwd,front,96.1,181.5,66.5,55.2,2579,ohc,four,132,mpfi,3.46,3.9,8.7,?,?,23,31,9295 133 | 2,?,renault,gas,std,two,hatchback,fwd,front,96.1,176.8,66.6,50.5,2460,ohc,four,132,mpfi,3.46,3.9,8.7,?,?,23,31,9895 134 | 3,150,saab,gas,std,two,hatchback,fwd,front,99.1,186.6,66.5,56.1,2658,ohc,four,121,mpfi,3.54,3.07,9.31,110,5250,21,28,11850 135 | 2,104,saab,gas,std,four,sedan,fwd,front,99.1,186.6,66.5,56.1,2695,ohc,four,121,mpfi,3.54,3.07,9.3,110,5250,21,28,12170 136 | 3,150,saab,gas,std,two,hatchback,fwd,front,99.1,186.6,66.5,56.1,2707,ohc,four,121,mpfi,2.54,2.07,9.3,110,5250,21,28,15040 137 | 2,104,saab,gas,std,four,sedan,fwd,front,99.1,186.6,66.5,56.1,2758,ohc,four,121,mpfi,3.54,3.07,9.3,110,5250,21,28,15510 138 | 3,150,saab,gas,turbo,two,hatchback,fwd,front,99.1,186.6,66.5,56.1,2808,dohc,four,121,mpfi,3.54,3.07,9,160,5500,19,26,18150 139 | 2,104,saab,gas,turbo,four,sedan,fwd,front,99.1,186.6,66.5,56.1,2847,dohc,four,121,mpfi,3.54,3.07,9,160,5500,19,26,18620 140 | 2,83,subaru,gas,std,two,hatchback,fwd,front,93.7,156.9,63.4,53.7,2050,ohcf,four,97,2bbl,3.62,2.36,9,69,4900,31,36,5118 141 | 2,83,subaru,gas,std,two,hatchback,fwd,front,93.7,157.9,63.6,53.7,2120,ohcf,four,108,2bbl,3.62,2.64,8.7,73,4400,26,31,7053 142 | 2,83,subaru,gas,std,two,hatchback,4wd,front,93.3,157.3,63.8,55.7,2240,ohcf,four,108,2bbl,3.62,2.64,8.7,73,4400,26,31,7603 143 | 0,102,subaru,gas,std,four,sedan,fwd,front,97.2,172,65.4,52.5,2145,ohcf,four,108,2bbl,3.62,2.64,9.5,82,4800,32,37,7126 144 | 0,102,subaru,gas,std,four,sedan,fwd,front,97.2,172,65.4,52.5,2190,ohcf,four,108,2bbl,3.62,2.64,9.5,82,4400,28,33,7775 145 | 0,102,subaru,gas,std,four,sedan,fwd,front,97.2,172,65.4,52.5,2340,ohcf,four,108,mpfi,3.62,2.64,9,94,5200,26,32,9960 146 | 0,102,subaru,gas,std,four,sedan,4wd,front,97,172,65.4,54.3,2385,ohcf,four,108,2bbl,3.62,2.64,9,82,4800,24,25,9233 147 | 0,102,subaru,gas,turbo,four,sedan,4wd,front,97,172,65.4,54.3,2510,ohcf,four,108,mpfi,3.62,2.64,7.7,111,4800,24,29,11259 148 | 0,89,subaru,gas,std,four,wagon,fwd,front,97,173.5,65.4,53,2290,ohcf,four,108,2bbl,3.62,2.64,9,82,4800,28,32,7463 149 | 0,89,subaru,gas,std,four,wagon,fwd,front,97,173.5,65.4,53,2455,ohcf,four,108,mpfi,3.62,2.64,9,94,5200,25,31,10198 150 | 0,85,subaru,gas,std,four,wagon,4wd,front,96.9,173.6,65.4,54.9,2420,ohcf,four,108,2bbl,3.62,2.64,9,82,4800,23,29,8013 151 | 0,85,subaru,gas,turbo,four,wagon,4wd,front,96.9,173.6,65.4,54.9,2650,ohcf,four,108,mpfi,3.62,2.64,7.7,111,4800,23,23,11694 152 | 1,87,toyota,gas,std,two,hatchback,fwd,front,95.7,158.7,63.6,54.5,1985,ohc,four,92,2bbl,3.05,3.03,9,62,4800,35,39,5348 153 | 1,87,toyota,gas,std,two,hatchback,fwd,front,95.7,158.7,63.6,54.5,2040,ohc,four,92,2bbl,3.05,3.03,9,62,4800,31,38,6338 154 | 1,74,toyota,gas,std,four,hatchback,fwd,front,95.7,158.7,63.6,54.5,2015,ohc,four,92,2bbl,3.05,3.03,9,62,4800,31,38,6488 155 | 0,77,toyota,gas,std,four,wagon,fwd,front,95.7,169.7,63.6,59.1,2280,ohc,four,92,2bbl,3.05,3.03,9,62,4800,31,37,6918 156 | 0,81,toyota,gas,std,four,wagon,4wd,front,95.7,169.7,63.6,59.1,2290,ohc,four,92,2bbl,3.05,3.03,9,62,4800,27,32,7898 157 | 0,91,toyota,gas,std,four,wagon,4wd,front,95.7,169.7,63.6,59.1,3110,ohc,four,92,2bbl,3.05,3.03,9,62,4800,27,32,8778 158 | 0,91,toyota,gas,std,four,sedan,fwd,front,95.7,166.3,64.4,53,2081,ohc,four,98,2bbl,3.19,3.03,9,70,4800,30,37,6938 159 | 0,91,toyota,gas,std,four,hatchback,fwd,front,95.7,166.3,64.4,52.8,2109,ohc,four,98,2bbl,3.19,3.03,9,70,4800,30,37,7198 160 | 0,91,toyota,diesel,std,four,sedan,fwd,front,95.7,166.3,64.4,53,2275,ohc,four,110,idi,3.27,3.35,22.5,56,4500,34,36,7898 161 | 0,91,toyota,diesel,std,four,hatchback,fwd,front,95.7,166.3,64.4,52.8,2275,ohc,four,110,idi,3.27,3.35,22.5,56,4500,38,47,7788 162 | 0,91,toyota,gas,std,four,sedan,fwd,front,95.7,166.3,64.4,53,2094,ohc,four,98,2bbl,3.19,3.03,9,70,4800,38,47,7738 163 | 0,91,toyota,gas,std,four,hatchback,fwd,front,95.7,166.3,64.4,52.8,2122,ohc,four,98,2bbl,3.19,3.03,9,70,4800,28,34,8358 164 | 0,91,toyota,gas,std,four,sedan,fwd,front,95.7,166.3,64.4,52.8,2140,ohc,four,98,2bbl,3.19,3.03,9,70,4800,28,34,9258 165 | 1,168,toyota,gas,std,two,sedan,rwd,front,94.5,168.7,64,52.6,2169,ohc,four,98,2bbl,3.19,3.03,9,70,4800,29,34,8058 166 | 1,168,toyota,gas,std,two,hatchback,rwd,front,94.5,168.7,64,52.6,2204,ohc,four,98,2bbl,3.19,3.03,9,70,4800,29,34,8238 167 | 1,168,toyota,gas,std,two,sedan,rwd,front,94.5,168.7,64,52.6,2265,dohc,four,98,mpfi,3.24,3.08,9.4,112,6600,26,29,9298 168 | 1,168,toyota,gas,std,two,hatchback,rwd,front,94.5,168.7,64,52.6,2300,dohc,four,98,mpfi,3.24,3.08,9.4,112,6600,26,29,9538 169 | 2,134,toyota,gas,std,two,hardtop,rwd,front,98.4,176.2,65.6,52,2540,ohc,four,146,mpfi,3.62,3.5,9.3,116,4800,24,30,8449 170 | 2,134,toyota,gas,std,two,hardtop,rwd,front,98.4,176.2,65.6,52,2536,ohc,four,146,mpfi,3.62,3.5,9.3,116,4800,24,30,9639 171 | 2,134,toyota,gas,std,two,hatchback,rwd,front,98.4,176.2,65.6,52,2551,ohc,four,146,mpfi,3.62,3.5,9.3,116,4800,24,30,9989 172 | 2,134,toyota,gas,std,two,hardtop,rwd,front,98.4,176.2,65.6,52,2679,ohc,four,146,mpfi,3.62,3.5,9.3,116,4800,24,30,11199 173 | 2,134,toyota,gas,std,two,hatchback,rwd,front,98.4,176.2,65.6,52,2714,ohc,four,146,mpfi,3.62,3.5,9.3,116,4800,24,30,11549 174 | 2,134,toyota,gas,std,two,convertible,rwd,front,98.4,176.2,65.6,53,2975,ohc,four,146,mpfi,3.62,3.5,9.3,116,4800,24,30,17669 175 | -1,65,toyota,gas,std,four,sedan,fwd,front,102.4,175.6,66.5,54.9,2326,ohc,four,122,mpfi,3.31,3.54,8.7,92,4200,29,34,8948 176 | -1,65,toyota,diesel,turbo,four,sedan,fwd,front,102.4,175.6,66.5,54.9,2480,ohc,four,110,idi,3.27,3.35,22.5,73,4500,30,33,10698 177 | -1,65,toyota,gas,std,four,hatchback,fwd,front,102.4,175.6,66.5,53.9,2414,ohc,four,122,mpfi,3.31,3.54,8.7,92,4200,27,32,9988 178 | -1,65,toyota,gas,std,four,sedan,fwd,front,102.4,175.6,66.5,54.9,2414,ohc,four,122,mpfi,3.31,3.54,8.7,92,4200,27,32,10898 179 | -1,65,toyota,gas,std,four,hatchback,fwd,front,102.4,175.6,66.5,53.9,2458,ohc,four,122,mpfi,3.31,3.54,8.7,92,4200,27,32,11248 180 | 3,197,toyota,gas,std,two,hatchback,rwd,front,102.9,183.5,67.7,52,2976,dohc,six,171,mpfi,3.27,3.35,9.3,161,5200,20,24,16558 181 | 3,197,toyota,gas,std,two,hatchback,rwd,front,102.9,183.5,67.7,52,3016,dohc,six,171,mpfi,3.27,3.35,9.3,161,5200,19,24,15998 182 | -1,90,toyota,gas,std,four,sedan,rwd,front,104.5,187.8,66.5,54.1,3131,dohc,six,171,mpfi,3.27,3.35,9.2,156,5200,20,24,15690 183 | -1,?,toyota,gas,std,four,wagon,rwd,front,104.5,187.8,66.5,54.1,3151,dohc,six,161,mpfi,3.27,3.35,9.2,156,5200,19,24,15750 184 | 2,122,volkswagen,diesel,std,two,sedan,fwd,front,97.3,171.7,65.5,55.7,2261,ohc,four,97,idi,3.01,3.4,23,52,4800,37,46,7775 185 | 2,122,volkswagen,gas,std,two,sedan,fwd,front,97.3,171.7,65.5,55.7,2209,ohc,four,109,mpfi,3.19,3.4,9,85,5250,27,34,7975 186 | 2,94,volkswagen,diesel,std,four,sedan,fwd,front,97.3,171.7,65.5,55.7,2264,ohc,four,97,idi,3.01,3.4,23,52,4800,37,46,7995 187 | 2,94,volkswagen,gas,std,four,sedan,fwd,front,97.3,171.7,65.5,55.7,2212,ohc,four,109,mpfi,3.19,3.4,9,85,5250,27,34,8195 188 | 2,94,volkswagen,gas,std,four,sedan,fwd,front,97.3,171.7,65.5,55.7,2275,ohc,four,109,mpfi,3.19,3.4,9,85,5250,27,34,8495 189 | 2,94,volkswagen,diesel,turbo,four,sedan,fwd,front,97.3,171.7,65.5,55.7,2319,ohc,four,97,idi,3.01,3.4,23,68,4500,37,42,9495 190 | 2,94,volkswagen,gas,std,four,sedan,fwd,front,97.3,171.7,65.5,55.7,2300,ohc,four,109,mpfi,3.19,3.4,10,100,5500,26,32,9995 191 | 3,?,volkswagen,gas,std,two,convertible,fwd,front,94.5,159.3,64.2,55.6,2254,ohc,four,109,mpfi,3.19,3.4,8.5,90,5500,24,29,11595 192 | 3,256,volkswagen,gas,std,two,hatchback,fwd,front,94.5,165.7,64,51.4,2221,ohc,four,109,mpfi,3.19,3.4,8.5,90,5500,24,29,9980 193 | 0,?,volkswagen,gas,std,four,sedan,fwd,front,100.4,180.2,66.9,55.1,2661,ohc,five,136,mpfi,3.19,3.4,8.5,110,5500,19,24,13295 194 | 0,?,volkswagen,diesel,turbo,four,sedan,fwd,front,100.4,180.2,66.9,55.1,2579,ohc,four,97,idi,3.01,3.4,23,68,4500,33,38,13845 195 | 0,?,volkswagen,gas,std,four,wagon,fwd,front,100.4,183.1,66.9,55.1,2563,ohc,four,109,mpfi,3.19,3.4,9,88,5500,25,31,12290 196 | -2,103,volvo,gas,std,four,sedan,rwd,front,104.3,188.8,67.2,56.2,2912,ohc,four,141,mpfi,3.78,3.15,9.5,114,5400,23,28,12940 197 | -1,74,volvo,gas,std,four,wagon,rwd,front,104.3,188.8,67.2,57.5,3034,ohc,four,141,mpfi,3.78,3.15,9.5,114,5400,23,28,13415 198 | -2,103,volvo,gas,std,four,sedan,rwd,front,104.3,188.8,67.2,56.2,2935,ohc,four,141,mpfi,3.78,3.15,9.5,114,5400,24,28,15985 199 | -1,74,volvo,gas,std,four,wagon,rwd,front,104.3,188.8,67.2,57.5,3042,ohc,four,141,mpfi,3.78,3.15,9.5,114,5400,24,28,16515 200 | -2,103,volvo,gas,turbo,four,sedan,rwd,front,104.3,188.8,67.2,56.2,3045,ohc,four,130,mpfi,3.62,3.15,7.5,162,5100,17,22,18420 201 | -1,74,volvo,gas,turbo,four,wagon,rwd,front,104.3,188.8,67.2,57.5,3157,ohc,four,130,mpfi,3.62,3.15,7.5,162,5100,17,22,18950 202 | -1,95,volvo,gas,std,four,sedan,rwd,front,109.1,188.8,68.9,55.5,2952,ohc,four,141,mpfi,3.78,3.15,9.5,114,5400,23,28,16845 203 | -1,95,volvo,gas,turbo,four,sedan,rwd,front,109.1,188.8,68.8,55.5,3049,ohc,four,141,mpfi,3.78,3.15,8.7,160,5300,19,25,19045 204 | -1,95,volvo,gas,std,four,sedan,rwd,front,109.1,188.8,68.9,55.5,3012,ohcv,six,173,mpfi,3.58,2.87,8.8,134,5500,18,23,21485 205 | -1,95,volvo,diesel,turbo,four,sedan,rwd,front,109.1,188.8,68.9,55.5,3217,ohc,six,145,idi,3.01,3.4,23,106,4800,26,27,22470 206 | -1,95,volvo,gas,turbo,four,sedan,rwd,front,109.1,188.8,68.9,55.5,3062,ohc,four,141,mpfi,3.78,3.15,9.5,114,5400,19,25,22625 207 | -------------------------------------------------------------------------------- /Chapter01/chapter 1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "### Chapter 1" 8 | ] 9 | }, 10 | { 11 | "cell_type": "code", 12 | "execution_count": 1, 13 | "metadata": {}, 14 | "outputs": [], 15 | "source": [ 16 | "def add(a,b):\n", 17 | " c = a + b\n", 18 | " return c" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "#### Scenario 1:" 26 | ] 27 | }, 28 | { 29 | "cell_type": "code", 30 | "execution_count": 2, 31 | "metadata": {}, 32 | "outputs": [ 33 | { 34 | "data": { 35 | "text/plain": [ 36 | "4" 37 | ] 38 | }, 39 | "execution_count": 2, 40 | "metadata": {}, 41 | "output_type": "execute_result" 42 | } 43 | ], 44 | "source": [ 45 | "add(1,3)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "metadata": {}, 51 | "source": [ 52 | "#### Scenario 2:" 53 | ] 54 | }, 55 | { 56 | "cell_type": "code", 57 | "execution_count": 3, 58 | "metadata": {}, 59 | "outputs": [ 60 | { 61 | "data": { 62 | "text/plain": [ 63 | "'metaprogram'" 64 | ] 65 | }, 66 | "execution_count": 3, 67 | "metadata": {}, 68 | "output_type": "execute_result" 69 | } 70 | ], 71 | "source": [ 72 | "add('meta','program')" 73 | ] 74 | }, 75 | { 76 | "cell_type": "markdown", 77 | "metadata": {}, 78 | "source": [ 79 | "#### Scenario 3:" 80 | ] 81 | }, 82 | { 83 | "cell_type": "code", 84 | "execution_count": 4, 85 | "metadata": {}, 86 | "outputs": [ 87 | { 88 | "ename": "TypeError", 89 | "evalue": "can only concatenate str (not \"int\") to str", 90 | "output_type": "error", 91 | "traceback": [ 92 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 93 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 94 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0madd\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;34m'meta'\u001b[0m\u001b[1;33m,\u001b[0m\u001b[1;36m1\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m", 95 | "\u001b[1;32m\u001b[0m in \u001b[0;36madd\u001b[1;34m(a, b)\u001b[0m\n\u001b[0;32m 1\u001b[0m \u001b[1;32mdef\u001b[0m \u001b[0madd\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[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 2\u001b[1;33m \u001b[0mc\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[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m 3\u001b[0m \u001b[1;32mreturn\u001b[0m \u001b[0mc\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 96 | "\u001b[1;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str" 97 | ] 98 | } 99 | ], 100 | "source": [ 101 | "add('meta',1)" 102 | ] 103 | }, 104 | { 105 | "cell_type": "markdown", 106 | "metadata": {}, 107 | "source": [ 108 | "#### Metadata of the function add" 109 | ] 110 | }, 111 | { 112 | "cell_type": "code", 113 | "execution_count": 5, 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "def add(a,b):\n", 118 | " c = a + b\n", 119 | " print (\"Metadata of add\", type(add))\n", 120 | " print (\"Metadata of a\", type(a))\n", 121 | " print (\"Metadata of b\", type(b))\n", 122 | " print (\"Metadata of c\", type(c))" 123 | ] 124 | }, 125 | { 126 | "cell_type": "code", 127 | "execution_count": 6, 128 | "metadata": {}, 129 | "outputs": [ 130 | { 131 | "name": "stdout", 132 | "output_type": "stream", 133 | "text": [ 134 | "Metadata of add \n", 135 | "Metadata of a \n", 136 | "Metadata of b \n", 137 | "Metadata of c \n" 138 | ] 139 | } 140 | ], 141 | "source": [ 142 | "add(1,3)" 143 | ] 144 | }, 145 | { 146 | "cell_type": "code", 147 | "execution_count": 7, 148 | "metadata": {}, 149 | "outputs": [ 150 | { 151 | "name": "stdout", 152 | "output_type": "stream", 153 | "text": [ 154 | "Metadata of add \n", 155 | "Metadata of a \n", 156 | "Metadata of b \n", 157 | "Metadata of c \n" 158 | ] 159 | } 160 | ], 161 | "source": [ 162 | "add('test','string')" 163 | ] 164 | }, 165 | { 166 | "cell_type": "markdown", 167 | "metadata": {}, 168 | "source": [ 169 | "### Solve using metaprogramming" 170 | ] 171 | }, 172 | { 173 | "cell_type": "markdown", 174 | "metadata": {}, 175 | "source": [ 176 | "#### Scenario 1" 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": 8, 182 | "metadata": {}, 183 | "outputs": [], 184 | "source": [ 185 | "def add(a,b):\n", 186 | " checkint = 1\n", 187 | " checkstr = 'test'\n", 188 | " if (type(a) is type(checkstr) and type(b) is type(checkint)) or\\\n", 189 | " (type(a) is type(checkint) and type(b) is type(checkstr)):\n", 190 | " return \"Please enter both input values as integers or string\"\n", 191 | " else:\n", 192 | " c = a + b\n", 193 | " return c" 194 | ] 195 | }, 196 | { 197 | "cell_type": "code", 198 | "execution_count": 9, 199 | "metadata": {}, 200 | "outputs": [ 201 | { 202 | "data": { 203 | "text/plain": [ 204 | "4" 205 | ] 206 | }, 207 | "execution_count": 9, 208 | "metadata": {}, 209 | "output_type": "execute_result" 210 | } 211 | ], 212 | "source": [ 213 | "add(1,3)" 214 | ] 215 | }, 216 | { 217 | "cell_type": "code", 218 | "execution_count": 10, 219 | "metadata": {}, 220 | "outputs": [ 221 | { 222 | "data": { 223 | "text/plain": [ 224 | "'metaprogram'" 225 | ] 226 | }, 227 | "execution_count": 10, 228 | "metadata": {}, 229 | "output_type": "execute_result" 230 | } 231 | ], 232 | "source": [ 233 | "add('meta','program')" 234 | ] 235 | }, 236 | { 237 | "cell_type": "code", 238 | "execution_count": 11, 239 | "metadata": {}, 240 | "outputs": [ 241 | { 242 | "data": { 243 | "text/plain": [ 244 | "'Please enter both input values as integers or string'" 245 | ] 246 | }, 247 | "execution_count": 11, 248 | "metadata": {}, 249 | "output_type": "execute_result" 250 | } 251 | ], 252 | "source": [ 253 | "add('meta',1)" 254 | ] 255 | }, 256 | { 257 | "cell_type": "code", 258 | "execution_count": 12, 259 | "metadata": {}, 260 | "outputs": [ 261 | { 262 | "data": { 263 | "text/plain": [ 264 | "'Please enter both input values as integers or string'" 265 | ] 266 | }, 267 | "execution_count": 12, 268 | "metadata": {}, 269 | "output_type": "execute_result" 270 | } 271 | ], 272 | "source": [ 273 | "add(1,'meta')" 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "metadata": {}, 279 | "source": [ 280 | "#### Scenario 2" 281 | ] 282 | }, 283 | { 284 | "cell_type": "code", 285 | "execution_count": 13, 286 | "metadata": {}, 287 | "outputs": [], 288 | "source": [ 289 | "def add(a,b):\n", 290 | " if type(a) is int and type(b) is int:\n", 291 | " c = a + b\n", 292 | " return c\n", 293 | " elif type(a) is str and type(b) is int or\\\n", 294 | " type(a) is int and type(b) is str or \\\n", 295 | " type(a) is str and type(b) is str:\n", 296 | " c = str(a) + str(b)\n", 297 | " return c\n", 298 | " else:\n", 299 | " print(\"Please enter string or integer\") " 300 | ] 301 | }, 302 | { 303 | "cell_type": "code", 304 | "execution_count": 14, 305 | "metadata": {}, 306 | "outputs": [ 307 | { 308 | "data": { 309 | "text/plain": [ 310 | "37132" 311 | ] 312 | }, 313 | "execution_count": 14, 314 | "metadata": {}, 315 | "output_type": "execute_result" 316 | } 317 | ], 318 | "source": [ 319 | "add(1343,35789)" 320 | ] 321 | }, 322 | { 323 | "cell_type": "code", 324 | "execution_count": 15, 325 | "metadata": {}, 326 | "outputs": [ 327 | { 328 | "data": { 329 | "text/plain": [ 330 | "'MetaProgramming'" 331 | ] 332 | }, 333 | "execution_count": 15, 334 | "metadata": {}, 335 | "output_type": "execute_result" 336 | } 337 | ], 338 | "source": [ 339 | "add('Meta','Programming')" 340 | ] 341 | }, 342 | { 343 | "cell_type": "code", 344 | "execution_count": 16, 345 | "metadata": {}, 346 | "outputs": [ 347 | { 348 | "data": { 349 | "text/plain": [ 350 | "'meta157676'" 351 | ] 352 | }, 353 | "execution_count": 16, 354 | "metadata": {}, 355 | "output_type": "execute_result" 356 | } 357 | ], 358 | "source": [ 359 | "add('meta',157676)" 360 | ] 361 | }, 362 | { 363 | "cell_type": "code", 364 | "execution_count": 17, 365 | "metadata": {}, 366 | "outputs": [ 367 | { 368 | "data": { 369 | "text/plain": [ 370 | "'65081meta'" 371 | ] 372 | }, 373 | "execution_count": 17, 374 | "metadata": {}, 375 | "output_type": "execute_result" 376 | } 377 | ], 378 | "source": [ 379 | "add(65081, 'meta')" 380 | ] 381 | }, 382 | { 383 | "cell_type": "code", 384 | "execution_count": 18, 385 | "metadata": {}, 386 | "outputs": [ 387 | { 388 | "name": "stdout", 389 | "output_type": "stream", 390 | "text": [ 391 | "Please enter string or integer\n" 392 | ] 393 | } 394 | ], 395 | "source": [ 396 | "add(True, 'meta')" 397 | ] 398 | }, 399 | { 400 | "cell_type": "markdown", 401 | "metadata": {}, 402 | "source": [ 403 | "#### Scenario 3" 404 | ] 405 | }, 406 | { 407 | "cell_type": "code", 408 | "execution_count": 19, 409 | "metadata": {}, 410 | "outputs": [], 411 | "source": [ 412 | "def add(a,b):\n", 413 | " if type(a) is int and type(b) is int or\\\n", 414 | " type(a) is float and type(b) is float or\\\n", 415 | " type(a) is int and type(b) is float or\\\n", 416 | " type(a) is float and type(b) is int:\n", 417 | " c = a + b\n", 418 | " return c\n", 419 | " else:\n", 420 | " return 'Please input numbers'" 421 | ] 422 | }, 423 | { 424 | "cell_type": "code", 425 | "execution_count": 20, 426 | "metadata": {}, 427 | "outputs": [ 428 | { 429 | "data": { 430 | "text/plain": [ 431 | "691126" 432 | ] 433 | }, 434 | "execution_count": 20, 435 | "metadata": {}, 436 | "output_type": "execute_result" 437 | } 438 | ], 439 | "source": [ 440 | "add(15443,675683)" 441 | ] 442 | }, 443 | { 444 | "cell_type": "code", 445 | "execution_count": 21, 446 | "metadata": {}, 447 | "outputs": [ 448 | { 449 | "data": { 450 | "text/plain": [ 451 | "54384.7876" 452 | ] 453 | }, 454 | "execution_count": 21, 455 | "metadata": {}, 456 | "output_type": "execute_result" 457 | } 458 | ], 459 | "source": [ 460 | "add(54381,3.7876)" 461 | ] 462 | }, 463 | { 464 | "cell_type": "code", 465 | "execution_count": 22, 466 | "metadata": {}, 467 | "outputs": [ 468 | { 469 | "data": { 470 | "text/plain": [ 471 | "550.5354" 472 | ] 473 | }, 474 | "execution_count": 22, 475 | "metadata": {}, 476 | "output_type": "execute_result" 477 | } 478 | ], 479 | "source": [ 480 | "add(6.7754,543.76)" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": 23, 486 | "metadata": {}, 487 | "outputs": [ 488 | { 489 | "data": { 490 | "text/plain": [ 491 | "79894.6568" 492 | ] 493 | }, 494 | "execution_count": 23, 495 | "metadata": {}, 496 | "output_type": "execute_result" 497 | } 498 | ], 499 | "source": [ 500 | "add(79894,0.6568)" 501 | ] 502 | }, 503 | { 504 | "cell_type": "code", 505 | "execution_count": 24, 506 | "metadata": {}, 507 | "outputs": [ 508 | { 509 | "data": { 510 | "text/plain": [ 511 | "'Please input numbers'" 512 | ] 513 | }, 514 | "execution_count": 24, 515 | "metadata": {}, 516 | "output_type": "execute_result" 517 | } 518 | ], 519 | "source": [ 520 | "add('meta',14684)" 521 | ] 522 | }, 523 | { 524 | "cell_type": "code", 525 | "execution_count": 25, 526 | "metadata": {}, 527 | "outputs": [ 528 | { 529 | "data": { 530 | "text/plain": [ 531 | "'Please input numbers'" 532 | ] 533 | }, 534 | "execution_count": 25, 535 | "metadata": {}, 536 | "output_type": "execute_result" 537 | } 538 | ], 539 | "source": [ 540 | "add(6576,'meta')" 541 | ] 542 | }, 543 | { 544 | "cell_type": "code", 545 | "execution_count": 26, 546 | "metadata": {}, 547 | "outputs": [ 548 | { 549 | "data": { 550 | "text/plain": [ 551 | "'Please input numbers'" 552 | ] 553 | }, 554 | "execution_count": 26, 555 | "metadata": {}, 556 | "output_type": "execute_result" 557 | } 558 | ], 559 | "source": [ 560 | "add('meta','program')" 561 | ] 562 | }, 563 | { 564 | "cell_type": "markdown", 565 | "metadata": {}, 566 | "source": [ 567 | "### Don't Repeat Yourself" 568 | ] 569 | }, 570 | { 571 | "cell_type": "code", 572 | "execution_count": 27, 573 | "metadata": {}, 574 | "outputs": [], 575 | "source": [ 576 | "def add(a,b):\n", 577 | " c = a + b\n", 578 | " return c\n", 579 | "\n", 580 | "def sub(a,b):\n", 581 | " c = a - b\n", 582 | " return c\n", 583 | "\n", 584 | "def multiply(a,b):\n", 585 | " c = a * b\n", 586 | " return c\n", 587 | "\n", 588 | "def divide(a,b):\n", 589 | " c = a / b\n", 590 | " return c" 591 | ] 592 | }, 593 | { 594 | "cell_type": "code", 595 | "execution_count": 28, 596 | "metadata": {}, 597 | "outputs": [ 598 | { 599 | "data": { 600 | "text/plain": [ 601 | "7" 602 | ] 603 | }, 604 | "execution_count": 28, 605 | "metadata": {}, 606 | "output_type": "execute_result" 607 | } 608 | ], 609 | "source": [ 610 | "add(2,5)" 611 | ] 612 | }, 613 | { 614 | "cell_type": "code", 615 | "execution_count": 29, 616 | "metadata": {}, 617 | "outputs": [ 618 | { 619 | "data": { 620 | "text/plain": [ 621 | "-3" 622 | ] 623 | }, 624 | "execution_count": 29, 625 | "metadata": {}, 626 | "output_type": "execute_result" 627 | } 628 | ], 629 | "source": [ 630 | "sub(2,5)" 631 | ] 632 | }, 633 | { 634 | "cell_type": "code", 635 | "execution_count": 30, 636 | "metadata": {}, 637 | "outputs": [ 638 | { 639 | "data": { 640 | "text/plain": [ 641 | "10" 642 | ] 643 | }, 644 | "execution_count": 30, 645 | "metadata": {}, 646 | "output_type": "execute_result" 647 | } 648 | ], 649 | "source": [ 650 | "multiply(2,5)" 651 | ] 652 | }, 653 | { 654 | "cell_type": "code", 655 | "execution_count": 31, 656 | "metadata": {}, 657 | "outputs": [ 658 | { 659 | "data": { 660 | "text/plain": [ 661 | "0.4" 662 | ] 663 | }, 664 | "execution_count": 31, 665 | "metadata": {}, 666 | "output_type": "execute_result" 667 | } 668 | ], 669 | "source": [ 670 | "divide(2,5)" 671 | ] 672 | }, 673 | { 674 | "cell_type": "markdown", 675 | "metadata": {}, 676 | "source": [ 677 | "### Alternative approach" 678 | ] 679 | }, 680 | { 681 | "cell_type": "code", 682 | "execution_count": 32, 683 | "metadata": {}, 684 | "outputs": [], 685 | "source": [ 686 | "import operator as op" 687 | ] 688 | }, 689 | { 690 | "cell_type": "code", 691 | "execution_count": 33, 692 | "metadata": {}, 693 | "outputs": [], 694 | "source": [ 695 | "def arithmetic(a, b, operation):\n", 696 | " result = operation(a, b)\n", 697 | " return result" 698 | ] 699 | }, 700 | { 701 | "cell_type": "code", 702 | "execution_count": 34, 703 | "metadata": {}, 704 | "outputs": [ 705 | { 706 | "data": { 707 | "text/plain": [ 708 | "'25'" 709 | ] 710 | }, 711 | "execution_count": 34, 712 | "metadata": {}, 713 | "output_type": "execute_result" 714 | } 715 | ], 716 | "source": [ 717 | "arithmetic('2', '5', op.add)" 718 | ] 719 | }, 720 | { 721 | "cell_type": "code", 722 | "execution_count": 35, 723 | "metadata": {}, 724 | "outputs": [ 725 | { 726 | "data": { 727 | "text/plain": [ 728 | "7" 729 | ] 730 | }, 731 | "execution_count": 35, 732 | "metadata": {}, 733 | "output_type": "execute_result" 734 | } 735 | ], 736 | "source": [ 737 | "arithmetic(2, 5, op.add)" 738 | ] 739 | }, 740 | { 741 | "cell_type": "code", 742 | "execution_count": 36, 743 | "metadata": {}, 744 | "outputs": [ 745 | { 746 | "data": { 747 | "text/plain": [ 748 | "-3" 749 | ] 750 | }, 751 | "execution_count": 36, 752 | "metadata": {}, 753 | "output_type": "execute_result" 754 | } 755 | ], 756 | "source": [ 757 | "arithmetic(2 , 5, op.sub)" 758 | ] 759 | }, 760 | { 761 | "cell_type": "code", 762 | "execution_count": 37, 763 | "metadata": {}, 764 | "outputs": [ 765 | { 766 | "data": { 767 | "text/plain": [ 768 | "10" 769 | ] 770 | }, 771 | "execution_count": 37, 772 | "metadata": {}, 773 | "output_type": "execute_result" 774 | } 775 | ], 776 | "source": [ 777 | "arithmetic(2, 5, op.mul)" 778 | ] 779 | }, 780 | { 781 | "cell_type": "code", 782 | "execution_count": 38, 783 | "metadata": {}, 784 | "outputs": [ 785 | { 786 | "data": { 787 | "text/plain": [ 788 | "0.4" 789 | ] 790 | }, 791 | "execution_count": 38, 792 | "metadata": {}, 793 | "output_type": "execute_result" 794 | } 795 | ], 796 | "source": [ 797 | "arithmetic(2 , 5, op.truediv)" 798 | ] 799 | }, 800 | { 801 | "cell_type": "markdown", 802 | "metadata": {}, 803 | "source": [ 804 | "### Dynamic Function Creation" 805 | ] 806 | }, 807 | { 808 | "cell_type": "code", 809 | "execution_count": 39, 810 | "metadata": {}, 811 | "outputs": [], 812 | "source": [ 813 | "from types import FunctionType" 814 | ] 815 | }, 816 | { 817 | "cell_type": "code", 818 | "execution_count": 40, 819 | "metadata": {}, 820 | "outputs": [], 821 | "source": [ 822 | "functionstring = '''\n", 823 | "def arithmetic(a, b):\n", 824 | " op = __import__('operator')\n", 825 | " result = op.add(a, b)\n", 826 | " return result\n", 827 | " '''" 828 | ] 829 | }, 830 | { 831 | "cell_type": "code", 832 | "execution_count": 41, 833 | "metadata": {}, 834 | "outputs": [ 835 | { 836 | "name": "stdout", 837 | "output_type": "stream", 838 | "text": [ 839 | "\n", 840 | "def arithmetic(a, b):\n", 841 | " op = __import__('operator')\n", 842 | " result = op.add(a, b)\n", 843 | " return result\n", 844 | " \n" 845 | ] 846 | } 847 | ], 848 | "source": [ 849 | "print(functionstring)" 850 | ] 851 | }, 852 | { 853 | "cell_type": "code", 854 | "execution_count": 42, 855 | "metadata": {}, 856 | "outputs": [], 857 | "source": [ 858 | "functiontemplate = compile(functionstring, 'functionstring', 'exec')" 859 | ] 860 | }, 861 | { 862 | "cell_type": "code", 863 | "execution_count": 43, 864 | "metadata": {}, 865 | "outputs": [ 866 | { 867 | "data": { 868 | "text/plain": [ 869 | " at 0x000001DFBF15D5B0, file \"functionstring\", line 2>" 870 | ] 871 | }, 872 | "execution_count": 43, 873 | "metadata": {}, 874 | "output_type": "execute_result" 875 | } 876 | ], 877 | "source": [ 878 | "functiontemplate" 879 | ] 880 | }, 881 | { 882 | "cell_type": "code", 883 | "execution_count": 44, 884 | "metadata": {}, 885 | "outputs": [ 886 | { 887 | "data": { 888 | "text/plain": [ 889 | "" 890 | ] 891 | }, 892 | "execution_count": 44, 893 | "metadata": {}, 894 | "output_type": "execute_result" 895 | } 896 | ], 897 | "source": [ 898 | "functiontemplate.co_consts[0]" 899 | ] 900 | }, 901 | { 902 | "cell_type": "code", 903 | "execution_count": 45, 904 | "metadata": {}, 905 | "outputs": [], 906 | "source": [ 907 | "dynamicfunction = FunctionType(functiontemplate.co_consts[0], globals(), \"add\")" 908 | ] 909 | }, 910 | { 911 | "cell_type": "code", 912 | "execution_count": 46, 913 | "metadata": {}, 914 | "outputs": [ 915 | { 916 | "data": { 917 | "text/plain": [ 918 | "" 919 | ] 920 | }, 921 | "execution_count": 46, 922 | "metadata": {}, 923 | "output_type": "execute_result" 924 | } 925 | ], 926 | "source": [ 927 | "dynamicfunction" 928 | ] 929 | }, 930 | { 931 | "cell_type": "code", 932 | "execution_count": 47, 933 | "metadata": {}, 934 | "outputs": [ 935 | { 936 | "data": { 937 | "text/plain": [ 938 | "7" 939 | ] 940 | }, 941 | "execution_count": 47, 942 | "metadata": {}, 943 | "output_type": "execute_result" 944 | } 945 | ], 946 | "source": [ 947 | "dynamicfunction(2,5)" 948 | ] 949 | }, 950 | { 951 | "cell_type": "code", 952 | "execution_count": 48, 953 | "metadata": {}, 954 | "outputs": [], 955 | "source": [ 956 | "a = 2\n", 957 | "b = 5\n", 958 | "\n", 959 | "operator = ['op.add','op.sub','op.mul','op.truediv','op.pow','op.mod', 'op.gt', 'op.lt']\n", 960 | "functionname = ['add','sub', 'multiply', 'divide', 'power', 'modulus', 'greaterthan', 'lesserthan']\n", 961 | "\n", 962 | "def functiongenerator(functionname, operator, a,b):\n", 963 | " from types import FunctionType\n", 964 | " functionstring = []\n", 965 | " for i in operator:\n", 966 | " functionstring.append('''\n", 967 | "def arithmetic(a, b):\n", 968 | " op = __import__('operator')\n", 969 | " result = '''+ i + '''(a, b)\n", 970 | " return result\n", 971 | " ''')\n", 972 | "\n", 973 | " functiontemplate = []\n", 974 | " for i in functionstring:\n", 975 | " functiontemplate.append(compile(i, 'functionstring', 'exec'))\n", 976 | "\n", 977 | " dynamicfunction = []\n", 978 | " for i,j in zip(functiontemplate,functionname):\n", 979 | " dynamicfunction.append(FunctionType(i.co_consts[0], globals(), j))\n", 980 | "\n", 981 | " functiondict = {}\n", 982 | " \n", 983 | " for i,j in zip(functionname,dynamicfunction):\n", 984 | " functiondict[i]=j\n", 985 | " \n", 986 | " for i in dynamicfunction:\n", 987 | " print (i(a,b))\n", 988 | " \n", 989 | " return functiondict" 990 | ] 991 | }, 992 | { 993 | "cell_type": "code", 994 | "execution_count": 49, 995 | "metadata": {}, 996 | "outputs": [ 997 | { 998 | "name": "stdout", 999 | "output_type": "stream", 1000 | "text": [ 1001 | "7\n", 1002 | "-3\n", 1003 | "10\n", 1004 | "0.4\n", 1005 | "32\n", 1006 | "2\n", 1007 | "False\n", 1008 | "True\n" 1009 | ] 1010 | } 1011 | ], 1012 | "source": [ 1013 | "funcdict = functiongenerator(functionname, operator, a,b)" 1014 | ] 1015 | }, 1016 | { 1017 | "cell_type": "code", 1018 | "execution_count": 50, 1019 | "metadata": {}, 1020 | "outputs": [ 1021 | { 1022 | "data": { 1023 | "text/plain": [ 1024 | "{'add': ,\n", 1025 | " 'sub': ,\n", 1026 | " 'multiply': ,\n", 1027 | " 'divide': ,\n", 1028 | " 'power': ,\n", 1029 | " 'modulus': ,\n", 1030 | " 'greaterthan': ,\n", 1031 | " 'lesserthan': }" 1032 | ] 1033 | }, 1034 | "execution_count": 50, 1035 | "metadata": {}, 1036 | "output_type": "execute_result" 1037 | } 1038 | ], 1039 | "source": [ 1040 | "funcdict" 1041 | ] 1042 | }, 1043 | { 1044 | "cell_type": "code", 1045 | "execution_count": 51, 1046 | "metadata": {}, 1047 | "outputs": [ 1048 | { 1049 | "data": { 1050 | "text/plain": [ 1051 | "0.4" 1052 | ] 1053 | }, 1054 | "execution_count": 51, 1055 | "metadata": {}, 1056 | "output_type": "execute_result" 1057 | } 1058 | ], 1059 | "source": [ 1060 | "funcdict['divide'](a,b)" 1061 | ] 1062 | }, 1063 | { 1064 | "cell_type": "code", 1065 | "execution_count": 52, 1066 | "metadata": {}, 1067 | "outputs": [ 1068 | { 1069 | "data": { 1070 | "text/plain": [ 1071 | "True" 1072 | ] 1073 | }, 1074 | "execution_count": 52, 1075 | "metadata": {}, 1076 | "output_type": "execute_result" 1077 | } 1078 | ], 1079 | "source": [ 1080 | "funcdict['lesserthan'](a,b)" 1081 | ] 1082 | }, 1083 | { 1084 | "cell_type": "code", 1085 | "execution_count": 53, 1086 | "metadata": {}, 1087 | "outputs": [ 1088 | { 1089 | "data": { 1090 | "text/plain": [ 1091 | "False" 1092 | ] 1093 | }, 1094 | "execution_count": 53, 1095 | "metadata": {}, 1096 | "output_type": "execute_result" 1097 | } 1098 | ], 1099 | "source": [ 1100 | "funcdict['greaterthan'](a,b)" 1101 | ] 1102 | }, 1103 | { 1104 | "cell_type": "markdown", 1105 | "metadata": {}, 1106 | "source": [ 1107 | "### These are all the examples covered in chapter 1" 1108 | ] 1109 | }, 1110 | { 1111 | "cell_type": "code", 1112 | "execution_count": null, 1113 | "metadata": {}, 1114 | "outputs": [], 1115 | "source": [] 1116 | } 1117 | ], 1118 | "metadata": { 1119 | "kernelspec": { 1120 | "display_name": "Python 3", 1121 | "language": "python", 1122 | "name": "python3" 1123 | }, 1124 | "language_info": { 1125 | "codemirror_mode": { 1126 | "name": "ipython", 1127 | "version": 3 1128 | }, 1129 | "file_extension": ".py", 1130 | "mimetype": "text/x-python", 1131 | "name": "python", 1132 | "nbconvert_exporter": "python", 1133 | "pygments_lexer": "ipython3", 1134 | "version": "3.9.5" 1135 | } 1136 | }, 1137 | "nbformat": 4, 1138 | "nbformat_minor": 4 1139 | } 1140 | -------------------------------------------------------------------------------- /Chapter10/chapter 10.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "a3580a72", 6 | "metadata": {}, 7 | "source": [ 8 | "## Chapter 10 MRO" 9 | ] 10 | }, 11 | { 12 | "cell_type": "markdown", 13 | "id": "508a1bcf", 14 | "metadata": {}, 15 | "source": [ 16 | "### Understanding MRO of a class" 17 | ] 18 | }, 19 | { 20 | "cell_type": "code", 21 | "execution_count": 3, 22 | "id": "f242d358", 23 | "metadata": {}, 24 | "outputs": [], 25 | "source": [ 26 | "class Branch:\n", 27 | " def __init__(self, branch_id, branch_street, branch_city, branch_state, branch_zip, product, sales, invoice):\n", 28 | " \n", 29 | " self.branch_id = branch_id\n", 30 | " self.branch_street = branch_street\n", 31 | " self.branch_city = branch_city\n", 32 | " self.branch_state = branch_state\n", 33 | " self.branch_zip = branch_zip\n", 34 | " self.product = product\n", 35 | " self.sales = sales\n", 36 | " self.invoice = invoice\n", 37 | " \n", 38 | " def get_product(self):\n", 39 | " return self.product\n", 40 | " \n", 41 | " def get_sales(self):\n", 42 | " return self.sales\n", 43 | " \n", 44 | " def get_invoice(self):\n", 45 | " return self.invoice" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": 2, 51 | "id": "999db5e8", 52 | "metadata": {}, 53 | "outputs": [ 54 | { 55 | "data": { 56 | "text/plain": [ 57 | "[__main__.Branch, object]" 58 | ] 59 | }, 60 | "execution_count": 2, 61 | "metadata": {}, 62 | "output_type": "execute_result" 63 | } 64 | ], 65 | "source": [ 66 | "Branch.mro()" 67 | ] 68 | }, 69 | { 70 | "cell_type": "markdown", 71 | "id": "c1ef5e9e", 72 | "metadata": {}, 73 | "source": [ 74 | "### Understanding MRO in Single inheritance" 75 | ] 76 | }, 77 | { 78 | "cell_type": "code", 79 | "execution_count": 27, 80 | "id": "4fb3286d", 81 | "metadata": {}, 82 | "outputs": [], 83 | "source": [ 84 | "class Branch:\n", 85 | "\n", 86 | " def __init__(self, branch, sales, product):\n", 87 | " self.branch = branch\n", 88 | " self.sales = sales\n", 89 | " self.product = product\n", 90 | " \n", 91 | " def set_branch(self, value):\n", 92 | " self.branch = value\n", 93 | " \n", 94 | " def set_sales(self, value):\n", 95 | " self.sales = value\n", 96 | " \n", 97 | " def set_product(self, value):\n", 98 | " self.product = value\n", 99 | " \n", 100 | " def calc_tax(self):\n", 101 | " branch = self.branch\n", 102 | " product = self.product\n", 103 | " sales = self.sales\n", 104 | " pricebeforetax = sales['purchase_price'] + sales['purchase_price'] * sales['profit_margin']\n", 105 | " finalselling_price = pricebeforetax + (pricebeforetax * sales['tax_rate'])\n", 106 | " sales['selling_price'] = finalselling_price\n", 107 | " return branch, product, sales" 108 | ] 109 | }, 110 | { 111 | "cell_type": "code", 112 | "execution_count": 28, 113 | "id": "bf859852", 114 | "metadata": {}, 115 | "outputs": [], 116 | "source": [ 117 | "class NYC(Branch):\n", 118 | " def __init__(self, intercitybranch):\n", 119 | " self.intercitybranch = intercitybranch\n", 120 | " \n", 121 | " def set_management(self, value):\n", 122 | " self.intercitybranch = value\n", 123 | " \n", 124 | " def calc_tax_nyc(self):\n", 125 | " branch = self.branch\n", 126 | " intercitybranch = self.intercitybranch\n", 127 | " product = self.product\n", 128 | " sales = self.sales\n", 129 | " pricebeforetax = sales['purchase_price'] + sales['purchase_price'] * sales['profit_margin']\n", 130 | " finalselling_price = pricebeforetax + (pricebeforetax * (sales['tax_rate'] + sales['local_rate'])) \n", 131 | " sales['selling_price'] = finalselling_price\n", 132 | " return branch, intercitybranch, product, sales " 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": 29, 138 | "id": "0576b3df", 139 | "metadata": {}, 140 | "outputs": [ 141 | { 142 | "data": { 143 | "text/plain": [ 144 | "[__main__.NYC, __main__.Branch, object]" 145 | ] 146 | }, 147 | "execution_count": 29, 148 | "metadata": {}, 149 | "output_type": "execute_result" 150 | } 151 | ], 152 | "source": [ 153 | "NYC.mro()" 154 | ] 155 | }, 156 | { 157 | "cell_type": "code", 158 | "execution_count": 37, 159 | "id": "e6f91347", 160 | "metadata": {}, 161 | "outputs": [], 162 | "source": [ 163 | "branch = {'branch_id' : 2021,\n", 164 | "'branch_street' : '40097 5th Main Street',\n", 165 | "'branchBorough' : 'Manhattan', \n", 166 | "'branch_city' : 'New York City',\n", 167 | "'branch_state' : 'New York',\n", 168 | "'branch_zip' : 11007}\n", 169 | "\n", 170 | "product = {'product_id' : 100002,\n", 171 | " 'product_name' : 'WashingMachine',\n", 172 | " 'productBrand' : 'Whirlpool' \n", 173 | "}\n", 174 | "\n", 175 | "sales = {\n", 176 | " 'purchase_price' : 450,\n", 177 | " 'profit_margin' : 0.19,\n", 178 | " 'tax_rate' : 0.4,\n", 179 | " 'local_rate' : 0.055 \n", 180 | "}\n", 181 | "\n", 182 | "intercitybranch = {\n", 183 | " \n", 184 | "}" 185 | ] 186 | }, 187 | { 188 | "cell_type": "code", 189 | "execution_count": 38, 190 | "id": "d420aac4", 191 | "metadata": {}, 192 | "outputs": [], 193 | "source": [ 194 | "branch_manhattan = NYC(intercitybranch)" 195 | ] 196 | }, 197 | { 198 | "cell_type": "code", 199 | "execution_count": 40, 200 | "id": "2f44285d", 201 | "metadata": {}, 202 | "outputs": [], 203 | "source": [ 204 | "branch_manhattan.set_management({'regionalManager' : 'John M',\n", 205 | " 'branchManager' : 'Tom H',\n", 206 | " 'subbranch_id' : '2021-01' })" 207 | ] 208 | }, 209 | { 210 | "cell_type": "code", 211 | "execution_count": 41, 212 | "id": "4f927c2b", 213 | "metadata": {}, 214 | "outputs": [], 215 | "source": [ 216 | "branch_manhattan.set_branch(branch)" 217 | ] 218 | }, 219 | { 220 | "cell_type": "code", 221 | "execution_count": 42, 222 | "id": "3becbfad", 223 | "metadata": {}, 224 | "outputs": [], 225 | "source": [ 226 | "branch_manhattan.set_product(product)" 227 | ] 228 | }, 229 | { 230 | "cell_type": "code", 231 | "execution_count": 43, 232 | "id": "a408c830", 233 | "metadata": {}, 234 | "outputs": [], 235 | "source": [ 236 | "branch_manhattan.set_sales(sales)" 237 | ] 238 | }, 239 | { 240 | "cell_type": "code", 241 | "execution_count": 36, 242 | "id": "99f1905f", 243 | "metadata": {}, 244 | "outputs": [ 245 | { 246 | "data": { 247 | "text/plain": [ 248 | "({'branch_id': 2021,\n", 249 | " 'branch_street': '40097 5th Main Street',\n", 250 | " 'branchBorough': 'Manhattan',\n", 251 | " 'branch_city': 'New York City',\n", 252 | " 'branch_state': 'New York',\n", 253 | " 'branch_zip': 11007},\n", 254 | " {'regionalManager': 'John M',\n", 255 | " 'branchManager': 'Tom H',\n", 256 | " 'subbranch_id': '2021-01'},\n", 257 | " {'productId': 100002,\n", 258 | " 'productName': 'WashingMachine',\n", 259 | " 'productBrand': 'Whirlpool'},\n", 260 | " {'purchase_price': 450,\n", 261 | " 'profit_margin': 0.19,\n", 262 | " 'tax_rate': 0.4,\n", 263 | " 'local_rate': 0.055,\n", 264 | " 'selling_price': 779.1525})" 265 | ] 266 | }, 267 | "execution_count": 36, 268 | "metadata": {}, 269 | "output_type": "execute_result" 270 | } 271 | ], 272 | "source": [ 273 | "branch_manhattan.calc_tax_nyc()" 274 | ] 275 | }, 276 | { 277 | "cell_type": "markdown", 278 | "id": "6e880034", 279 | "metadata": {}, 280 | "source": [ 281 | "### Understanding MRO in Multiple inheritance" 282 | ] 283 | }, 284 | { 285 | "cell_type": "code", 286 | "execution_count": 44, 287 | "id": "fa90ebd8", 288 | "metadata": {}, 289 | "outputs": [], 290 | "source": [ 291 | "class Product:\n", 292 | " _product_id = 100902\n", 293 | " _product_name = 'Iphone X'\n", 294 | " _product_category = 'Electronics'\n", 295 | " _unit_price = 700\n", 296 | " \n", 297 | " def get_product(self):\n", 298 | " return self._product_id, self._product_name, self._product_category, self._unit_price\n", 299 | "\n", 300 | "class Branch:\n", 301 | " _branch_id = 2021\n", 302 | " _branch_street = '40097 5th Main Street'\n", 303 | " _branch_borough = 'Manhattan'\n", 304 | " _branch_city = 'New York City'\n", 305 | " _branch_state = 'New York'\n", 306 | " _branch_zip = 11007\n", 307 | " \n", 308 | " def get_branch(self):\n", 309 | " return self._branch_id, self._branch_street, self._branch_borough, self._branch_city, self._branch_state, self._branch_zip\n", 310 | " " 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": 45, 316 | "id": "6174a242", 317 | "metadata": {}, 318 | "outputs": [], 319 | "source": [ 320 | "class Sales(Product, Branch):\n", 321 | " date = '08/02/2021'\n", 322 | " def get_sales(self):\n", 323 | " return self.date, Product.get_product(self), Branch.get_branch(self)\n" 324 | ] 325 | }, 326 | { 327 | "cell_type": "code", 328 | "execution_count": 46, 329 | "id": "c0bdaea6", 330 | "metadata": {}, 331 | "outputs": [ 332 | { 333 | "data": { 334 | "text/plain": [ 335 | "[__main__.Sales, __main__.Product, __main__.Branch, object]" 336 | ] 337 | }, 338 | "execution_count": 46, 339 | "metadata": {}, 340 | "output_type": "execute_result" 341 | } 342 | ], 343 | "source": [ 344 | "Sales.mro()" 345 | ] 346 | }, 347 | { 348 | "cell_type": "code", 349 | "execution_count": 47, 350 | "id": "0126f708", 351 | "metadata": {}, 352 | "outputs": [], 353 | "source": [ 354 | "class Invoice(Branch, Product):\n", 355 | " date = '08/02/2021'\n", 356 | " def get_invoice(self):\n", 357 | " return self.date, Branch.get_branch(self), Product.get_product(self)" 358 | ] 359 | }, 360 | { 361 | "cell_type": "code", 362 | "execution_count": 48, 363 | "id": "4f0b0b1c", 364 | "metadata": {}, 365 | "outputs": [ 366 | { 367 | "data": { 368 | "text/plain": [ 369 | "[__main__.Invoice, __main__.Branch, __main__.Product, object]" 370 | ] 371 | }, 372 | "execution_count": 48, 373 | "metadata": {}, 374 | "output_type": "execute_result" 375 | } 376 | ], 377 | "source": [ 378 | "Invoice.mro()" 379 | ] 380 | }, 381 | { 382 | "cell_type": "markdown", 383 | "id": "bdfe7141", 384 | "metadata": {}, 385 | "source": [ 386 | "### Reviewing MRO in Multilevel inheritance" 387 | ] 388 | }, 389 | { 390 | "cell_type": "code", 391 | "execution_count": 49, 392 | "id": "6f0beb03", 393 | "metadata": {}, 394 | "outputs": [], 395 | "source": [ 396 | "class StoreCoupon:\n", 397 | " product_name = \"Strawberry Ice Cream\"\n", 398 | " product_category = \"Desserts\"\n", 399 | " brand = \"ABCBrand3\"\n", 400 | " store = \"Los Angeles Store\"\n", 401 | " expiry_date = \"10/1/2021\"\n", 402 | " quantity = 10\n", 403 | " \n", 404 | " def generate_coupon(self):\n", 405 | " import random\n", 406 | " coupon_id = random.sample(range(100000000000,900000000000),2)\n", 407 | " for i in coupon_id:\n", 408 | " print('***********------------------**************')\n", 409 | " print('Product:', self.product_name)\n", 410 | " print('Product Category:', self.product_category)\n", 411 | " print('Coupon ID:', i)\n", 412 | " print('Brand:', self.brand)\n", 413 | " print('Store:', self.store)\n", 414 | " print('Expiry Date:', self.expiry_date)\n", 415 | " print('Quantity:', self.quantity)\n", 416 | " print('***********------------------**************')" 417 | ] 418 | }, 419 | { 420 | "cell_type": "code", 421 | "execution_count": 50, 422 | "id": "986e962c", 423 | "metadata": {}, 424 | "outputs": [], 425 | "source": [ 426 | "class SendStoreCoupon(StoreCoupon):\n", 427 | " pass" 428 | ] 429 | }, 430 | { 431 | "cell_type": "code", 432 | "execution_count": 51, 433 | "id": "8a0cce86", 434 | "metadata": {}, 435 | "outputs": [ 436 | { 437 | "data": { 438 | "text/plain": [ 439 | "[__main__.SendStoreCoupon, __main__.StoreCoupon, object]" 440 | ] 441 | }, 442 | "execution_count": 51, 443 | "metadata": {}, 444 | "output_type": "execute_result" 445 | } 446 | ], 447 | "source": [ 448 | "SendStoreCoupon.mro()" 449 | ] 450 | }, 451 | { 452 | "cell_type": "code", 453 | "execution_count": 52, 454 | "id": "9e6db220", 455 | "metadata": {}, 456 | "outputs": [], 457 | "source": [ 458 | "class SendCoupon(SendStoreCoupon):\n", 459 | " pass" 460 | ] 461 | }, 462 | { 463 | "cell_type": "code", 464 | "execution_count": 53, 465 | "id": "b50a239a", 466 | "metadata": {}, 467 | "outputs": [ 468 | { 469 | "data": { 470 | "text/plain": [ 471 | "[__main__.SendCoupon, __main__.SendStoreCoupon, __main__.StoreCoupon, object]" 472 | ] 473 | }, 474 | "execution_count": 53, 475 | "metadata": {}, 476 | "output_type": "execute_result" 477 | } 478 | ], 479 | "source": [ 480 | "SendCoupon.mro()" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": 54, 486 | "id": "2df48ee4", 487 | "metadata": {}, 488 | "outputs": [], 489 | "source": [ 490 | "coupon = SendCoupon()" 491 | ] 492 | }, 493 | { 494 | "cell_type": "code", 495 | "execution_count": 55, 496 | "id": "553ed018", 497 | "metadata": {}, 498 | "outputs": [ 499 | { 500 | "name": "stdout", 501 | "output_type": "stream", 502 | "text": [ 503 | "***********------------------**************\n", 504 | "Product: Strawberry Ice Cream\n", 505 | "Product Category: Desserts\n", 506 | "Coupon ID: 350310591693\n", 507 | "Brand: ABCBrand3\n", 508 | "Store: Los Angeles Store\n", 509 | "Expiry Date: 10/1/2021\n", 510 | "Quantity: 10\n", 511 | "***********------------------**************\n", 512 | "***********------------------**************\n", 513 | "Product: Strawberry Ice Cream\n", 514 | "Product Category: Desserts\n", 515 | "Coupon ID: 316535403307\n", 516 | "Brand: ABCBrand3\n", 517 | "Store: Los Angeles Store\n", 518 | "Expiry Date: 10/1/2021\n", 519 | "Quantity: 10\n", 520 | "***********------------------**************\n" 521 | ] 522 | } 523 | ], 524 | "source": [ 525 | "coupon.generate_coupon()" 526 | ] 527 | }, 528 | { 529 | "cell_type": "markdown", 530 | "id": "30e62317", 531 | "metadata": {}, 532 | "source": [ 533 | "### Understanding the impact of modifying the order of inheritance" 534 | ] 535 | }, 536 | { 537 | "cell_type": "code", 538 | "execution_count": 56, 539 | "id": "06b313ab", 540 | "metadata": {}, 541 | "outputs": [], 542 | "source": [ 543 | "class ManufacturerCoupon:\n", 544 | " product_name = \"Strawberry Ice Cream\"\n", 545 | " product_category = \"Desserts\"\n", 546 | " brand = \"ABCBrand3\"\n", 547 | " manufacturer = \"ABC Manufacturer\"\n", 548 | " expiry_date = \"10/1/2021\"\n", 549 | " quantity = 10\n", 550 | " \n", 551 | " def generate_coupon(self):\n", 552 | " import random\n", 553 | " coupon_id = random.sample(range(100000000000,900000000000),2)\n", 554 | " for i in coupon_id:\n", 555 | " print('***********------------------**************')\n", 556 | " print('Product:', self.product_name)\n", 557 | " print('Product Category:', self.product_category)\n", 558 | " print('Coupon ID:', i)\n", 559 | " print('Brand:', self.brand)\n", 560 | " print('Manufacturer:', self.manufacturer)\n", 561 | " print('Expiry Date:', self.expiry_date)\n", 562 | " print('Quantity:', self.quantity)\n", 563 | " print('***********------------------**************')" 564 | ] 565 | }, 566 | { 567 | "cell_type": "code", 568 | "execution_count": 57, 569 | "id": "af0523ef", 570 | "metadata": {}, 571 | "outputs": [], 572 | "source": [ 573 | "class SendCoupon(ManufacturerCoupon,SendStoreCoupon):\n", 574 | " pass" 575 | ] 576 | }, 577 | { 578 | "cell_type": "code", 579 | "execution_count": 58, 580 | "id": "753e3516", 581 | "metadata": {}, 582 | "outputs": [ 583 | { 584 | "data": { 585 | "text/plain": [ 586 | "[__main__.SendCoupon,\n", 587 | " __main__.ManufacturerCoupon,\n", 588 | " __main__.SendStoreCoupon,\n", 589 | " __main__.StoreCoupon,\n", 590 | " object]" 591 | ] 592 | }, 593 | "execution_count": 58, 594 | "metadata": {}, 595 | "output_type": "execute_result" 596 | } 597 | ], 598 | "source": [ 599 | "SendCoupon.mro()" 600 | ] 601 | }, 602 | { 603 | "cell_type": "code", 604 | "execution_count": 59, 605 | "id": "fe186ecd", 606 | "metadata": {}, 607 | "outputs": [], 608 | "source": [ 609 | "coupon = SendCoupon()" 610 | ] 611 | }, 612 | { 613 | "cell_type": "code", 614 | "execution_count": 60, 615 | "id": "7d3b238b", 616 | "metadata": {}, 617 | "outputs": [ 618 | { 619 | "name": "stdout", 620 | "output_type": "stream", 621 | "text": [ 622 | "***********------------------**************\n", 623 | "Product: Strawberry Ice Cream\n", 624 | "Product Category: Desserts\n", 625 | "Coupon ID: 126214201699\n", 626 | "Brand: ABCBrand3\n", 627 | "Manufacturer: ABC Manufacturer\n", 628 | "Expiry Date: 10/1/2021\n", 629 | "Quantity: 10\n", 630 | "***********------------------**************\n", 631 | "***********------------------**************\n", 632 | "Product: Strawberry Ice Cream\n", 633 | "Product Category: Desserts\n", 634 | "Coupon ID: 602247613557\n", 635 | "Brand: ABCBrand3\n", 636 | "Manufacturer: ABC Manufacturer\n", 637 | "Expiry Date: 10/1/2021\n", 638 | "Quantity: 10\n", 639 | "***********------------------**************\n" 640 | ] 641 | } 642 | ], 643 | "source": [ 644 | "coupon.generate_coupon()" 645 | ] 646 | }, 647 | { 648 | "cell_type": "code", 649 | "execution_count": 61, 650 | "id": "9756f05a", 651 | "metadata": {}, 652 | "outputs": [], 653 | "source": [ 654 | "class SendCoupon(SendStoreCoupon,ManufacturerCoupon):\n", 655 | " pass" 656 | ] 657 | }, 658 | { 659 | "cell_type": "code", 660 | "execution_count": 62, 661 | "id": "1c3ececb", 662 | "metadata": {}, 663 | "outputs": [ 664 | { 665 | "data": { 666 | "text/plain": [ 667 | "[__main__.SendCoupon,\n", 668 | " __main__.SendStoreCoupon,\n", 669 | " __main__.StoreCoupon,\n", 670 | " __main__.ManufacturerCoupon,\n", 671 | " object]" 672 | ] 673 | }, 674 | "execution_count": 62, 675 | "metadata": {}, 676 | "output_type": "execute_result" 677 | } 678 | ], 679 | "source": [ 680 | "SendCoupon.mro()" 681 | ] 682 | }, 683 | { 684 | "cell_type": "code", 685 | "execution_count": 63, 686 | "id": "e7dec7c1", 687 | "metadata": {}, 688 | "outputs": [], 689 | "source": [ 690 | "coupon = SendCoupon()" 691 | ] 692 | }, 693 | { 694 | "cell_type": "code", 695 | "execution_count": 64, 696 | "id": "441a0e39", 697 | "metadata": {}, 698 | "outputs": [ 699 | { 700 | "name": "stdout", 701 | "output_type": "stream", 702 | "text": [ 703 | "***********------------------**************\n", 704 | "Product: Strawberry Ice Cream\n", 705 | "Product Category: Desserts\n", 706 | "Coupon ID: 733105674376\n", 707 | "Brand: ABCBrand3\n", 708 | "Store: Los Angeles Store\n", 709 | "Expiry Date: 10/1/2021\n", 710 | "Quantity: 10\n", 711 | "***********------------------**************\n", 712 | "***********------------------**************\n", 713 | "Product: Strawberry Ice Cream\n", 714 | "Product Category: Desserts\n", 715 | "Coupon ID: 715805912307\n", 716 | "Brand: ABCBrand3\n", 717 | "Store: Los Angeles Store\n", 718 | "Expiry Date: 10/1/2021\n", 719 | "Quantity: 10\n", 720 | "***********------------------**************\n" 721 | ] 722 | } 723 | ], 724 | "source": [ 725 | "coupon.generate_coupon()" 726 | ] 727 | }, 728 | { 729 | "cell_type": "markdown", 730 | "id": "c33803bd", 731 | "metadata": {}, 732 | "source": [ 733 | "### Impact of unintended change of order in inheritance" 734 | ] 735 | }, 736 | { 737 | "cell_type": "code", 738 | "execution_count": 65, 739 | "id": "5ab090f7", 740 | "metadata": {}, 741 | "outputs": [], 742 | "source": [ 743 | "class CommonCounter():\n", 744 | " def __init__(self,items,name):\n", 745 | " self.items = items\n", 746 | " self.name = name\n", 747 | " \n", 748 | " def return_cart(self):\n", 749 | " cartItems = self.items\n", 750 | " return cartItems\n", 751 | " \n", 752 | " def goto_counter(self):\n", 753 | " countername = self.name\n", 754 | " return countername" 755 | ] 756 | }, 757 | { 758 | "cell_type": "code", 759 | "execution_count": 66, 760 | "id": "b660491e", 761 | "metadata": {}, 762 | "outputs": [ 763 | { 764 | "data": { 765 | "text/plain": [ 766 | "[__main__.CommonCounter, object]" 767 | ] 768 | }, 769 | "execution_count": 66, 770 | "metadata": {}, 771 | "output_type": "execute_result" 772 | } 773 | ], 774 | "source": [ 775 | "CommonCounter.mro()" 776 | ] 777 | }, 778 | { 779 | "cell_type": "code", 780 | "execution_count": 67, 781 | "id": "d8ff5f80", 782 | "metadata": {}, 783 | "outputs": [], 784 | "source": [ 785 | "class CheckItems():\n", 786 | " def __init__(self, item_type = None):\n", 787 | " self.item_type = item_type\n", 788 | " \n", 789 | " def review_items(self, item_type = None):\n", 790 | " veg_cart = ['Vegetables', 'Dairy', 'Fruits']\n", 791 | " if (item_type == 'Electronics'):\n", 792 | " print(\"Move to Electronics Counter\")\n", 793 | " elif (item_type in veg_cart): \n", 794 | " print(\"Move to Vege Counter\")" 795 | ] 796 | }, 797 | { 798 | "cell_type": "code", 799 | "execution_count": 68, 800 | "id": "668a1392", 801 | "metadata": {}, 802 | "outputs": [ 803 | { 804 | "data": { 805 | "text/plain": [ 806 | "[__main__.CheckItems, object]" 807 | ] 808 | }, 809 | "execution_count": 68, 810 | "metadata": {}, 811 | "output_type": "execute_result" 812 | } 813 | ], 814 | "source": [ 815 | "CheckItems.mro()" 816 | ] 817 | }, 818 | { 819 | "cell_type": "code", 820 | "execution_count": 72, 821 | "id": "d60fbad6", 822 | "metadata": {}, 823 | "outputs": [], 824 | "source": [ 825 | "class ElectronicsCounter(CommonCounter,CheckItems):\n", 826 | " def __init__(status = None):\n", 827 | " self.status = status\n", 828 | " \n", 829 | " def test_electronics(self):\n", 830 | " teststatus = []\n", 831 | " for i in self.status:\n", 832 | " teststatus.append(i)\n", 833 | " return teststatus" 834 | ] 835 | }, 836 | { 837 | "cell_type": "code", 838 | "execution_count": 73, 839 | "id": "20dfcd54", 840 | "metadata": {}, 841 | "outputs": [ 842 | { 843 | "data": { 844 | "text/plain": [ 845 | "[__main__.ElectronicsCounter,\n", 846 | " __main__.CommonCounter,\n", 847 | " __main__.CheckItems,\n", 848 | " object]" 849 | ] 850 | }, 851 | "execution_count": 73, 852 | "metadata": {}, 853 | "output_type": "execute_result" 854 | } 855 | ], 856 | "source": [ 857 | "ElectronicsCounter.mro()" 858 | ] 859 | }, 860 | { 861 | "cell_type": "code", 862 | "execution_count": 74, 863 | "id": "903a6105", 864 | "metadata": {}, 865 | "outputs": [], 866 | "source": [ 867 | "class VegeCounter(CheckItems,CommonCounter):\n", 868 | " def __init__(weights = None):\n", 869 | " self.weights = weights\n", 870 | " \n", 871 | " def weigh_items(self):\n", 872 | " item_weight = dict(zip(self.items, self.weights))\n", 873 | " return item_weight" 874 | ] 875 | }, 876 | { 877 | "cell_type": "code", 878 | "execution_count": 75, 879 | "id": "710f24b0", 880 | "metadata": {}, 881 | "outputs": [ 882 | { 883 | "data": { 884 | "text/plain": [ 885 | "[__main__.VegeCounter, __main__.CheckItems, __main__.CommonCounter, object]" 886 | ] 887 | }, 888 | "execution_count": 75, 889 | "metadata": {}, 890 | "output_type": "execute_result" 891 | } 892 | ], 893 | "source": [ 894 | "VegeCounter.mro()" 895 | ] 896 | }, 897 | { 898 | "cell_type": "code", 899 | "execution_count": 76, 900 | "id": "0002d595", 901 | "metadata": {}, 902 | "outputs": [ 903 | { 904 | "ename": "TypeError", 905 | "evalue": "Cannot create a consistent method resolution\norder (MRO) for bases CommonCounter, CheckItems", 906 | "output_type": "error", 907 | "traceback": [ 908 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 909 | "\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)", 910 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[1;32mclass\u001b[0m \u001b[0mScanCode\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mElectronicsCounter\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mVegeCounter\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[0m\u001b[0;32m 2\u001b[0m \u001b[1;32mpass\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n", 911 | "\u001b[1;31mTypeError\u001b[0m: Cannot create a consistent method resolution\norder (MRO) for bases CommonCounter, CheckItems" 912 | ] 913 | } 914 | ], 915 | "source": [ 916 | "class ScanCode(ElectronicsCounter,VegeCounter):\n", 917 | " pass" 918 | ] 919 | }, 920 | { 921 | "cell_type": "code", 922 | "execution_count": 77, 923 | "id": "af262491", 924 | "metadata": {}, 925 | "outputs": [ 926 | { 927 | "ename": "NameError", 928 | "evalue": "name 'ScanCode' is not defined", 929 | "output_type": "error", 930 | "traceback": [ 931 | "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m", 932 | "\u001b[1;31mNameError\u001b[0m Traceback (most recent call last)", 933 | "\u001b[1;32m\u001b[0m in \u001b[0;36m\u001b[1;34m\u001b[0m\n\u001b[1;32m----> 1\u001b[1;33m \u001b[0mScanCode\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mmro\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[0m", 934 | "\u001b[1;31mNameError\u001b[0m: name 'ScanCode' is not defined" 935 | ] 936 | } 937 | ], 938 | "source": [ 939 | "ScanCode.mro()" 940 | ] 941 | }, 942 | { 943 | "cell_type": "markdown", 944 | "id": "a22e3fcf", 945 | "metadata": {}, 946 | "source": [ 947 | "### These are the examples covered in Chapter 10" 948 | ] 949 | } 950 | ], 951 | "metadata": { 952 | "kernelspec": { 953 | "display_name": "Python 3", 954 | "language": "python", 955 | "name": "python3" 956 | }, 957 | "language_info": { 958 | "codemirror_mode": { 959 | "name": "ipython", 960 | "version": 3 961 | }, 962 | "file_extension": ".py", 963 | "mimetype": "text/x-python", 964 | "name": "python", 965 | "nbconvert_exporter": "python", 966 | "pygments_lexer": "ipython3", 967 | "version": "3.9.5" 968 | } 969 | }, 970 | "nbformat": 4, 971 | "nbformat_minor": 5 972 | } 973 | -------------------------------------------------------------------------------- /Chapter08/chapter8.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Chapter 8 - Templates" 8 | ] 9 | }, 10 | { 11 | "cell_type": "markdown", 12 | "metadata": {}, 13 | "source": [ 14 | "## Vegetable counter - Definition" 15 | ] 16 | }, 17 | { 18 | "cell_type": "code", 19 | "execution_count": 1, 20 | "metadata": {}, 21 | "outputs": [], 22 | "source": [ 23 | "def return_cart(*items):\n", 24 | " cart_items = []\n", 25 | " for i in items:\n", 26 | " cart_items.append(i)\n", 27 | " return cart_items" 28 | ] 29 | }, 30 | { 31 | "cell_type": "code", 32 | "execution_count": 2, 33 | "metadata": {}, 34 | "outputs": [], 35 | "source": [ 36 | "def return_cart(*items):\n", 37 | " return list(items)" 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": 3, 43 | "metadata": {}, 44 | "outputs": [], 45 | "source": [ 46 | "return_cart('onions','tomatoes','carrots','lettuce')" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": 4, 52 | "metadata": {}, 53 | "outputs": [], 54 | "source": [ 55 | "class VegCounter():\n", 56 | " def return_cart(self,*items):\n", 57 | " cart_items = list(items)\n", 58 | " return cart_items\n", 59 | " \n", 60 | " def goto_vege_counter(self):\n", 61 | " return 'Vegetables & Dairy'\n", 62 | " \n", 63 | " def weigh_items(self,*weights,cart_items = None):\n", 64 | " weight = list(weights)\n", 65 | " item_weight = dict(zip(cart_items, weight))\n", 66 | " return item_weight\n", 67 | " \n", 68 | " def add_price_tag(self,*units,weights = None):\n", 69 | " pricetag = []\n", 70 | " for item,price in zip(weights.items(),list(units)):\n", 71 | " pricetag.append(item[1]*price)\n", 72 | " return pricetag\n", 73 | " \n", 74 | " def scan_bar_code(self,*scan):\n", 75 | " codes = list(scan)\n", 76 | " return codes\n", 77 | " \n", 78 | " def add_billing(self,codes=None,pricetag=None):\n", 79 | " self.codes = codes\n", 80 | " self.pricetag = pricetag\n", 81 | " bill = dict(zip(self.codes, self.pricetag))\n", 82 | " return bill\n", 83 | " \n", 84 | " def add_tax(self,*tax):\n", 85 | " taxed = list(tax)\n", 86 | " return taxed\n", 87 | " \n", 88 | " def calc_bill(self,bill,taxes,cart_items):\n", 89 | " items = []\n", 90 | " calc_bill = []\n", 91 | " for item,tax in zip(bill.items(),taxes):\n", 92 | " items.append(item[1])\n", 93 | " calc_bill.append(item[1] + item[1]*tax)\n", 94 | " finalbill = dict(zip(cart_items, calc_bill))\n", 95 | " return finalbill\n", 96 | " \n", 97 | " def print_invoice(self,finalbill):\n", 98 | " final_total = sum(finalbill.values())\n", 99 | " print('**************ABC Megamart*****************')\n", 100 | " print('***********------------------**************')\n", 101 | " print('Counter Name: ', self.goto_vege_counter())\n", 102 | " for item,price in finalbill.items():\n", 103 | " print(item,\": \", price)\n", 104 | " print('Total:',final_total)\n", 105 | " print('***********------------------**************')\n", 106 | " \n", 107 | " def receive_payment(self,finalbill):\n", 108 | " final_total = sum(finalbill.values())\n", 109 | " print('**************ABC Megamart*****************')\n", 110 | " print('***********------------------**************')\n", 111 | " print('Counter Name: ', self.goto_vege_counter())\n", 112 | " for item,price in finalbill.items():\n", 113 | " print(item,\": \", price)\n", 114 | " print('Total:',final_total)\n", 115 | " print('***********------------------**************')\n", 116 | " print('***************PAID************************')" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 5, 122 | "metadata": {}, 123 | "outputs": [], 124 | "source": [ 125 | "veg = VegCounter()\n", 126 | "cart = veg.return_cart('onions','tomatoes','carrots','lettuce')\n", 127 | "item_weight = veg.weigh_items(1,2,1.5,2.5,cart_items = cart)\n", 128 | "pricetag = veg.add_price_tag(7,2,3,5,weights = item_weight)\n", 129 | "codes = veg.scan_bar_code(113323,3434332,2131243,2332783)\n", 130 | "bill = veg.add_billing(codes,pricetag)\n", 131 | "taxes = veg.add_tax(0.04,0.03,0.035,0.025)\n", 132 | "finalbill = veg.calc_bill(bill,taxes,cart)" 133 | ] 134 | }, 135 | { 136 | "cell_type": "code", 137 | "execution_count": 6, 138 | "metadata": {}, 139 | "outputs": [], 140 | "source": [ 141 | "veg.print_invoice(finalbill)" 142 | ] 143 | }, 144 | { 145 | "cell_type": "code", 146 | "execution_count": 7, 147 | "metadata": {}, 148 | "outputs": [], 149 | "source": [ 150 | "veg.receive_payment(finalbill)" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": {}, 156 | "source": [ 157 | "## Less than 10 items counter" 158 | ] 159 | }, 160 | { 161 | "cell_type": "code", 162 | "execution_count": 8, 163 | "metadata": {}, 164 | "outputs": [], 165 | "source": [ 166 | "class LessThan10Counter():\n", 167 | " def return_cart(self,*items):\n", 168 | " cart_items = list(items)\n", 169 | " return cart_items\n", 170 | " \n", 171 | " def goto_less_t10_counter(self):\n", 172 | " return 'Less than 10 counter'\n", 173 | " \n", 174 | " def review_items(self,item_type = None):\n", 175 | " veg_cart = ['Vegetables', 'Dairy', 'Fruits']\n", 176 | " if (item_type == 'Electronics'):\n", 177 | " print(\"Move to Electronics Counter\")\n", 178 | " elif (item_type in veg_cart): \n", 179 | " print(\"Move to Vege Counter\")\n", 180 | " \n", 181 | " def count_items(self,cart_items = None):\n", 182 | " if len(cart_items)<=10:\n", 183 | " print(\"Move to Less than 10 items counter\")\n", 184 | " else:\n", 185 | " print(\"Move to Greater than 10 items counter\")\n", 186 | " \n", 187 | " def scan_bar_code(self,*scan):\n", 188 | " codes = list(scan)\n", 189 | " return codes\n", 190 | " \n", 191 | " def add_billing(self,*units,codes=None):\n", 192 | " pricetag = []\n", 193 | " for i in units:\n", 194 | " pricetag.append(i)\n", 195 | " bill = dict(zip(codes, pricetag))\n", 196 | " return bill\n", 197 | " \n", 198 | " def add_tax(self,*tax):\n", 199 | " taxed = list(tax)\n", 200 | " return taxed\n", 201 | " \n", 202 | " def calc_bill(self,bill,taxes,cart_items):\n", 203 | " items = []\n", 204 | " cart_items = cart_items\n", 205 | " calc_bill = []\n", 206 | " for item,tax in zip(bill.items(),taxes):\n", 207 | " items.append(item[1])\n", 208 | " calc_bill.append(item[1] + item[1]*tax)\n", 209 | " finalbill = dict(zip(cart_items, calc_bill))\n", 210 | " return finalbill\n", 211 | " \n", 212 | " def print_invoice(self,finalbill):\n", 213 | " final_total = sum(finalbill.values())\n", 214 | " print('**************ABC Megamart*****************')\n", 215 | " print('***********------------------**************')\n", 216 | " print('Counter Name: ', self.goto_less_t10_counter())\n", 217 | " for item,price in finalbill.items():\n", 218 | " print(item,\": \", price)\n", 219 | " print('Total:',final_total)\n", 220 | " print('***********------------------**************')\n", 221 | " \n", 222 | " def receive_payment(self,finalbill):\n", 223 | " final_total = sum(finalbill.values())\n", 224 | " print('**************ABC Megamart*****************')\n", 225 | " print('***********------------------**************')\n", 226 | " print('Counter Name: ', self.goto_less_t10_counter())\n", 227 | " for item,price in finalbill.items():\n", 228 | " print(item,\": \", price)\n", 229 | " print('Total:',final_total)\n", 230 | " print('***********------------------**************')\n", 231 | " print('***************PAID************************')" 232 | ] 233 | }, 234 | { 235 | "cell_type": "code", 236 | "execution_count": 9, 237 | "metadata": {}, 238 | "outputs": [], 239 | "source": [ 240 | "less10 = LessThan10Counter()\n", 241 | "cart = less10.return_cart('paperclips','blue pens','stapler','pencils')\n", 242 | "less10.review_items(item_type = ['stationary'])\n", 243 | "less10.count_items(cart)\n", 244 | "codes = less10.scan_bar_code(113323,3434332,2131243,2332783)\n", 245 | "bill = less10.add_billing(10,15,12,14,codes = codes)\n", 246 | "taxes = less10.add_tax(0.04,0.03,0.035,0.025)\n", 247 | "finalbill = less10.calc_bill(bill,taxes,cart)" 248 | ] 249 | }, 250 | { 251 | "cell_type": "code", 252 | "execution_count": 10, 253 | "metadata": {}, 254 | "outputs": [], 255 | "source": [ 256 | "less10.print_invoice(finalbill)" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": 11, 262 | "metadata": {}, 263 | "outputs": [], 264 | "source": [ 265 | "less10.receive_payment(finalbill)" 266 | ] 267 | }, 268 | { 269 | "cell_type": "markdown", 270 | "metadata": {}, 271 | "source": [ 272 | "## Greater than 10 items counter" 273 | ] 274 | }, 275 | { 276 | "cell_type": "code", 277 | "execution_count": 12, 278 | "metadata": {}, 279 | "outputs": [], 280 | "source": [ 281 | "class GreaterThan10Counter():\n", 282 | " def return_cart(self,*items):\n", 283 | " cart_items = list(items)\n", 284 | " return cart_items\n", 285 | " \n", 286 | " def goto_greater_t10_counter(self):\n", 287 | " return 'Greater than 10 counter'\n", 288 | " \n", 289 | " def review_items(self,item_type = None):\n", 290 | " veg_cart = ['Vegetables', 'Dairy', 'Fruits']\n", 291 | " if (item_type == 'Electronics'):\n", 292 | " print(\"Move to Electronics Counter\")\n", 293 | " elif (item_type in veg_cart): \n", 294 | " print(\"Move to Vege Counter\")\n", 295 | " \n", 296 | " def count_items(self,cart_items = None):\n", 297 | " if len(cart_items)>10:\n", 298 | " print(\"Move to Greater than 10 items counter\")\n", 299 | " else:\n", 300 | " print(\"Move to Less than 10 items counter\")\n", 301 | " \n", 302 | " def scan_bar_code(self,*scan):\n", 303 | " codes = list(scan)\n", 304 | " return codes\n", 305 | " \n", 306 | " def add_billing(self,*units,codes=None):\n", 307 | " self.codes = codes\n", 308 | " pricetag = []\n", 309 | " for i in units:\n", 310 | " pricetag.append(i)\n", 311 | " bill = dict(zip(self.codes, pricetag))\n", 312 | " return bill\n", 313 | " \n", 314 | " def apply_coupon(self):\n", 315 | " coupon_discount = 0.1\n", 316 | " return coupon_discount \n", 317 | " \n", 318 | " def add_tax(self,*tax):\n", 319 | " taxed = list(tax)\n", 320 | " return taxed\n", 321 | " \n", 322 | " def calc_bill(self,bill,taxes,cart_items):\n", 323 | " items = []\n", 324 | " cart_items = cart_items\n", 325 | " calc_bill = []\n", 326 | " for item,tax in zip(bill.items(),taxes):\n", 327 | " items.append(item[1])\n", 328 | " calc_bill.append(item[1] + item[1]*tax)\n", 329 | " finalbill = dict(zip(cart_items, calc_bill))\n", 330 | " return finalbill\n", 331 | " \n", 332 | " def print_invoice(self,finalbill):\n", 333 | " final_total = sum(finalbill.values())\n", 334 | " print('**************ABC Megamart*****************')\n", 335 | " print('***********------------------**************')\n", 336 | " print('Counter Name: ', self.goto_greater_t10_counter())\n", 337 | " for item,price in finalbill.items():\n", 338 | " print(item,\": \", price)\n", 339 | " print('Total:',final_total - final_total * self.apply_coupon())\n", 340 | " print('***********------------------**************')\n", 341 | " \n", 342 | " def receive_payment(self,finalbill):\n", 343 | " final_total = sum(finalbill.values())\n", 344 | " print('**************ABC Megamart*****************')\n", 345 | " print('***********------------------**************')\n", 346 | " print('Counter Name: ', self.goto_greater_t10_counter())\n", 347 | " for item,price in finalbill.items():\n", 348 | " print(item,\": \", price)\n", 349 | " print('Total:',final_total - final_total * self.apply_coupon())\n", 350 | " print('***********------------------**************')\n", 351 | " print('***************PAID************************')" 352 | ] 353 | }, 354 | { 355 | "cell_type": "code", 356 | "execution_count": 13, 357 | "metadata": {}, 358 | "outputs": [], 359 | "source": [ 360 | "greater = GreaterThan10Counter()\n", 361 | "cart = greater.return_cart('paper clips','blue pens','stapler','pencils','a4paper','a3paper','chart',\n", 362 | " 'sketch pens','canvas','water color','acrylic colors')\n", 363 | "greater.review_items(item_type = ['stationary'])\n", 364 | "greater.count_items(cart)" 365 | ] 366 | }, 367 | { 368 | "cell_type": "code", 369 | "execution_count": 14, 370 | "metadata": {}, 371 | "outputs": [], 372 | "source": [ 373 | "codes = greater.scan_bar_code(113323,3434332,2131243,2332783)\n", 374 | "bill = greater.add_billing(10,15,12,14,codes = codes)\n", 375 | "taxes = greater.add_tax(0.04,0.03,0.035,0.025)\n", 376 | "greater.apply_coupon()" 377 | ] 378 | }, 379 | { 380 | "cell_type": "code", 381 | "execution_count": 15, 382 | "metadata": {}, 383 | "outputs": [], 384 | "source": [ 385 | "finalbill = greater.calc_bill(bill,taxes,cart)" 386 | ] 387 | }, 388 | { 389 | "cell_type": "code", 390 | "execution_count": 16, 391 | "metadata": {}, 392 | "outputs": [], 393 | "source": [ 394 | "greater.print_invoice(finalbill)" 395 | ] 396 | }, 397 | { 398 | "cell_type": "code", 399 | "execution_count": 17, 400 | "metadata": {}, 401 | "outputs": [], 402 | "source": [ 403 | "greater.receive_payment(finalbill)" 404 | ] 405 | }, 406 | { 407 | "cell_type": "markdown", 408 | "metadata": {}, 409 | "source": [ 410 | "## Electronics Counter" 411 | ] 412 | }, 413 | { 414 | "cell_type": "code", 415 | "execution_count": 18, 416 | "metadata": {}, 417 | "outputs": [], 418 | "source": [ 419 | "class ElectronicsCounter():\n", 420 | " def return_cart(self,*items):\n", 421 | " cart_items = list(items)\n", 422 | " return cart_items\n", 423 | " \n", 424 | " def goto_electronics_counter(self):\n", 425 | " return 'Electronics counter'\n", 426 | " \n", 427 | " def review_items(self,item_type = None):\n", 428 | " veg_cart = ['Vegetables', 'Dairy', 'Fruits']\n", 429 | " if (item_type == 'Electronics'):\n", 430 | " print(\"Move to Electronics Counter\")\n", 431 | " elif (item_type in veg_cart): \n", 432 | " print(\"Move to Vege Counter\")\n", 433 | " \n", 434 | " def test_electronics(self,*status):\n", 435 | " teststatus = list(status)\n", 436 | " return teststatus\n", 437 | " \n", 438 | " def scan_bar_code(self,*scan):\n", 439 | " codes = list(scan)\n", 440 | " return codes\n", 441 | " \n", 442 | " def add_billing(self,*units,codes=None):\n", 443 | " self.codes = codes\n", 444 | " pricetag = []\n", 445 | " for i in units:\n", 446 | " pricetag.append(i)\n", 447 | " bill = dict(zip(self.codes, pricetag))\n", 448 | " return bill\n", 449 | " \n", 450 | " def add_tax(self,*tax):\n", 451 | " taxed = list(tax)\n", 452 | " return taxed\n", 453 | " \n", 454 | " def apply_coupon(self):\n", 455 | " coupon_discount = 0.1\n", 456 | " return coupon_discount\n", 457 | " \n", 458 | " def calc_bill(self,bill,taxes,cart_items):\n", 459 | " items = []\n", 460 | " calc_bill = []\n", 461 | " for item,tax in zip(bill.items(),taxes):\n", 462 | " items.append(item[1])\n", 463 | " calc_bill.append(item[1] + item[1]*tax)\n", 464 | " finalbill = dict(zip(cart_items, calc_bill))\n", 465 | " return finalbill\n", 466 | " \n", 467 | " def print_invoice(self,finalbill):\n", 468 | " final_total = sum(finalbill.values())\n", 469 | " print('**************ABC Megamart*****************')\n", 470 | " print('***********------------------**************')\n", 471 | " print('Counter Name: ', self.goto_electronics_counter())\n", 472 | " for item,price in finalbill.items():\n", 473 | " print(item,\": \", price)\n", 474 | " print('Total:',final_total - final_total * self.apply_coupon())\n", 475 | " print('***********------------------**************')\n", 476 | " \n", 477 | " def receive_payment(self,finalbill):\n", 478 | " final_total = sum(finalbill.values())\n", 479 | " print('**************ABC Megamart*****************')\n", 480 | " print('***********------------------**************')\n", 481 | " print('Counter Name: ', self.goto_electronics_counter())\n", 482 | " for item,price in finalbill.items():\n", 483 | " print(item,\": \", price)\n", 484 | " print('Total:',final_total)\n", 485 | " print('***********------------------**************')\n", 486 | " print('***************PAID************************')" 487 | ] 488 | }, 489 | { 490 | "cell_type": "code", 491 | "execution_count": 19, 492 | "metadata": {}, 493 | "outputs": [], 494 | "source": [ 495 | "electronics = ElectronicsCounter()\n", 496 | "cart = electronics.return_cart('television','keyboard','mouse')\n", 497 | "electronics.review_items(item_type = ['Electronics'])\n", 498 | "electronics.test_electronics('pass','pass','pass')" 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": 20, 504 | "metadata": {}, 505 | "outputs": [], 506 | "source": [ 507 | "codes = electronics.scan_bar_code(113323,3434332,2131243)\n", 508 | "bill = electronics.add_billing(100,16,14,codes = codes)\n", 509 | "taxes = electronics.add_tax(0.04,0.03,0.035)\n", 510 | "electronics.apply_coupon()" 511 | ] 512 | }, 513 | { 514 | "cell_type": "code", 515 | "execution_count": 21, 516 | "metadata": {}, 517 | "outputs": [], 518 | "source": [ 519 | "finalbill = electronics.calc_bill(bill,taxes,cart)" 520 | ] 521 | }, 522 | { 523 | "cell_type": "code", 524 | "execution_count": 22, 525 | "metadata": {}, 526 | "outputs": [ 527 | { 528 | "name": "stdout", 529 | "output_type": "stream", 530 | "text": [ 531 | "**************ABC Megamart*****************\n", 532 | "***********------------------**************\n", 533 | "Counter Name: Electronics counter\n", 534 | "television : 104.0\n", 535 | "keyboard : 16.48\n", 536 | "mouse : 14.49\n", 537 | "Total: 121.473\n", 538 | "***********------------------**************\n" 539 | ] 540 | } 541 | ], 542 | "source": [ 543 | "electronics.print_invoice(finalbill)" 544 | ] 545 | }, 546 | { 547 | "cell_type": "code", 548 | "execution_count": 23, 549 | "metadata": {}, 550 | "outputs": [ 551 | { 552 | "name": "stdout", 553 | "output_type": "stream", 554 | "text": [ 555 | "**************ABC Megamart*****************\n", 556 | "***********------------------**************\n", 557 | "Counter Name: Electronics counter\n", 558 | "television : 104.0\n", 559 | "keyboard : 16.48\n", 560 | "mouse : 14.49\n", 561 | "Total: 134.97\n", 562 | "***********------------------**************\n", 563 | "***************PAID************************\n" 564 | ] 565 | } 566 | ], 567 | "source": [ 568 | "electronics.receive_payment(finalbill)" 569 | ] 570 | }, 571 | { 572 | "cell_type": "markdown", 573 | "metadata": {}, 574 | "source": [ 575 | "### Templates" 576 | ] 577 | }, 578 | { 579 | "cell_type": "code", 580 | "execution_count": 24, 581 | "metadata": {}, 582 | "outputs": [], 583 | "source": [ 584 | "from abc import ABC, abstractmethod \n", 585 | "\n", 586 | "class CommonCounter(ABC):\n", 587 | " def __init__(self,items,name,scan,units,tax,item_type = None, weights = None, status = None):\n", 588 | " self.items = items\n", 589 | " self.name = name\n", 590 | " self.scan = scan\n", 591 | " self.units = units\n", 592 | " self.tax = tax\n", 593 | " self.item_type = item_type\n", 594 | " self.weights = weights\n", 595 | " self.status = status\n", 596 | " \n", 597 | " def return_cart(self):\n", 598 | " cart_items = []\n", 599 | " for i in self.items:\n", 600 | " cart_items.append(i)\n", 601 | " return cart_items\n", 602 | " \n", 603 | " def goto_counter(self):\n", 604 | " countername = self.name\n", 605 | " return countername\n", 606 | "\n", 607 | " def scan_bar_code(self):\n", 608 | " codes = []\n", 609 | " for i in self.scan:\n", 610 | " codes.append(i)\n", 611 | " return codes\n", 612 | " \n", 613 | " def add_billing(self):\n", 614 | " self.codes = self.scan_bar_code()\n", 615 | " pricetag = []\n", 616 | " for i in self.units:\n", 617 | " pricetag.append(i)\n", 618 | " bill = dict(zip(self.codes, pricetag))\n", 619 | " return bill\n", 620 | " \n", 621 | " def add_tax(self):\n", 622 | " taxed = []\n", 623 | " for i in self.tax:\n", 624 | " taxed.append(i)\n", 625 | " return taxed\n", 626 | " \n", 627 | " def calc_bill(self):\n", 628 | " bill = self.add_billing()\n", 629 | " items = []\n", 630 | " cart_items = self.return_cart()\n", 631 | " calc_bill = []\n", 632 | " taxes = self.add_tax()\n", 633 | " for item,tax in zip(bill.items(),taxes):\n", 634 | " items.append(item[1])\n", 635 | " calc_bill.append(item[1] + item[1]*tax)\n", 636 | " finalbill = dict(zip(cart_items, calc_bill))\n", 637 | " return finalbill\n", 638 | " \n", 639 | " def receive_payment(self):\n", 640 | " finalbill = self.calc_bill()\n", 641 | " final_total = sum(finalbill.values())\n", 642 | " print('**************ABC Megamart*****************')\n", 643 | " print('***********------------------**************')\n", 644 | " print('Counter Name: ', self.goto_counter())\n", 645 | " for item,price in finalbill.items():\n", 646 | " print(item,\": \", price)\n", 647 | " print('Total:',final_total)\n", 648 | " print('***********------------------**************')\n", 649 | " print('***************PAID************************')\n", 650 | " \n", 651 | " def apply_coupon(self):\n", 652 | " return 0\n", 653 | " \n", 654 | " def weigh_items(self):\n", 655 | " pass\n", 656 | " \n", 657 | " def add_price_tag(self):\n", 658 | " pass\n", 659 | " \n", 660 | " def count_items(self):\n", 661 | " pass\n", 662 | " \n", 663 | " def test_electronics(self):\n", 664 | " pass\n", 665 | " \n", 666 | " @abstractmethod\n", 667 | " def review_items(self):\n", 668 | " pass\n", 669 | " \n", 670 | " def pipeline_template(self):\n", 671 | " self.return_cart()\n", 672 | " self.goto_counter()\n", 673 | " self.review_items()\n", 674 | " self.count_items()\n", 675 | " self.test_electronics()\n", 676 | " self.weigh_items()\n", 677 | " self.add_price_tag()\n", 678 | " self.scan_bar_code()\n", 679 | " self.add_billing()\n", 680 | " self.add_tax()\n", 681 | " self.apply_coupon()\n", 682 | " self.calc_bill()\n", 683 | " self.receive_payment()" 684 | ] 685 | }, 686 | { 687 | "cell_type": "code", 688 | "execution_count": 25, 689 | "metadata": {}, 690 | "outputs": [], 691 | "source": [ 692 | "class VegeCounter(CommonCounter):\n", 693 | " def review_items(self):\n", 694 | " if (self.item_type in ['Vegetables', 'Dairy', 'Fruits']):\n", 695 | " print(\"Move to Vege Counter\")\n", 696 | "\n", 697 | " def weigh_items(self):\n", 698 | " item_weight = dict(zip(self.items, self.weights))\n", 699 | " return item_weight\n", 700 | " \n", 701 | " def add_price_tag(self):\n", 702 | " pricetag = []\n", 703 | " item_weight = self.weigh_items()\n", 704 | " for item,price in zip(item_weight.items(),self.units):\n", 705 | " pricetag.append(item[1]*price)\n", 706 | " return pricetag " 707 | ] 708 | }, 709 | { 710 | "cell_type": "code", 711 | "execution_count": 26, 712 | "metadata": {}, 713 | "outputs": [], 714 | "source": [ 715 | "class ElectronicsCounter(CommonCounter):\n", 716 | " def review_items(self):\n", 717 | " if ('Electronics' in self.item_type):\n", 718 | " print(\"Move to Electronics Counter\")\n", 719 | " \n", 720 | " def test_electronics(self):\n", 721 | " teststatus = []\n", 722 | " for i in self.status:\n", 723 | " teststatus.append(i)\n", 724 | " return teststatus" 725 | ] 726 | }, 727 | { 728 | "cell_type": "code", 729 | "execution_count": 27, 730 | "metadata": {}, 731 | "outputs": [], 732 | "source": [ 733 | "def run_pipeline(counter = CommonCounter):\n", 734 | " counter.pipeline_template()" 735 | ] 736 | }, 737 | { 738 | "cell_type": "code", 739 | "execution_count": 28, 740 | "metadata": {}, 741 | "outputs": [ 742 | { 743 | "name": "stdout", 744 | "output_type": "stream", 745 | "text": [ 746 | "**************ABC Megamart*****************\n", 747 | "***********------------------**************\n", 748 | "Counter Name: ['Vegetable Counter']\n", 749 | "paperclips : 10.4\n", 750 | "blue pens : 15.45\n", 751 | "stapler : 12.42\n", 752 | "pencils : 14.35\n", 753 | "Total: 52.620000000000005\n", 754 | "***********------------------**************\n", 755 | "***************PAID************************\n" 756 | ] 757 | } 758 | ], 759 | "source": [ 760 | "run_pipeline(VegeCounter(items = ['onions','lettuce','apples','oranges'],\n", 761 | " name = ['Vegetable Counter'],\n", 762 | " scan = [113323,3434332,2131243,2332783],\n", 763 | " units = [10,15,12,14],\n", 764 | " tax = [0.04,0.03,0.035,0.025],\n", 765 | " item_type = ['Vegetables'],\n", 766 | " weights = [1,2,1.5,2.5]))" 767 | ] 768 | }, 769 | { 770 | "cell_type": "code", 771 | "execution_count": 29, 772 | "metadata": {}, 773 | "outputs": [ 774 | { 775 | "name": "stdout", 776 | "output_type": "stream", 777 | "text": [ 778 | "Move to Electronics Counter\n", 779 | "**************ABC Megamart*****************\n", 780 | "***********------------------**************\n", 781 | "Counter Name: ['Electronics Counter']\n", 782 | "television : 104.0\n", 783 | "keyboard : 16.48\n", 784 | "mouse : 14.49\n", 785 | "Total: 134.97\n", 786 | "***********------------------**************\n", 787 | "***************PAID************************\n" 788 | ] 789 | } 790 | ], 791 | "source": [ 792 | "run_pipeline(ElectronicsCounter(items = ['television','keyboard','mouse'],\n", 793 | " name = ['Electronics Counter'],\n", 794 | " scan = [113323,3434332,2131243],\n", 795 | " units = [100,16,14],\n", 796 | " tax = [0.04,0.03,0.035],\n", 797 | " item_type = ['Electronics'],\n", 798 | " status = ['pass','pass','pass']))" 799 | ] 800 | }, 801 | { 802 | "cell_type": "markdown", 803 | "metadata": {}, 804 | "source": [ 805 | "### These are all the examples covered in Chapter 8" 806 | ] 807 | } 808 | ], 809 | "metadata": { 810 | "kernelspec": { 811 | "display_name": "Python 3", 812 | "language": "python", 813 | "name": "python3" 814 | }, 815 | "language_info": { 816 | "codemirror_mode": { 817 | "name": "ipython", 818 | "version": 3 819 | }, 820 | "file_extension": ".py", 821 | "mimetype": "text/x-python", 822 | "name": "python", 823 | "nbconvert_exporter": "python", 824 | "pygments_lexer": "ipython3", 825 | "version": "3.8.5" 826 | } 827 | }, 828 | "nbformat": 4, 829 | "nbformat_minor": 5 830 | } 831 | --------------------------------------------------------------------------------