├── 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 |
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 |
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", 230 | " | classname | \n", 231 | "fuel_type | \n", 232 | "aspiration | \n", 233 | "num_of_door | \n", 234 | "drive_wheels | \n", 235 | "wheel_base | \n", 236 | "length | \n", 237 | "width | \n", 238 | "height | \n", 239 | "curb_weight | \n", 240 | "fuel_system | \n", 241 | "city_mpg | \n", 242 | "highway_mpg | \n", 243 | "price | \n", 244 | "
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| 12 | \n", 249 | "Honda12 | \n", 250 | "gas | \n", 251 | "std | \n", 252 | "four | \n", 253 | "fwd | \n", 254 | "96.5 | \n", 255 | "163.4 | \n", 256 | "64.0 | \n", 257 | "54.5 | \n", 258 | "2010 | \n", 259 | "1bbl | \n", 260 | "30 | \n", 261 | "34 | \n", 262 | "7295 | \n", 263 | "
| 49 | \n", 266 | "Toyota49 | \n", 267 | "gas | \n", 268 | "std | \n", 269 | "two | \n", 270 | "rwd | \n", 271 | "98.4 | \n", 272 | "176.2 | \n", 273 | "65.6 | \n", 274 | "53.0 | \n", 275 | "2975 | \n", 276 | "mpfi | \n", 277 | "24 | \n", 278 | "30 | \n", 279 | "17669 | \n", 280 | "
| 54 | \n", 283 | "Volvo54 | \n", 284 | "gas | \n", 285 | "std | \n", 286 | "four | \n", 287 | "rwd | \n", 288 | "104.3 | \n", 289 | "188.8 | \n", 290 | "67.2 | \n", 291 | "56.2 | \n", 292 | "2912 | \n", 293 | "mpfi | \n", 294 | "23 | \n", 295 | "28 | \n", 296 | "12940 | \n", 297 | "
| 25 | \n", 300 | "Mitsubishi25 | \n", 301 | "gas | \n", 302 | "std | \n", 303 | "four | \n", 304 | "fwd | \n", 305 | "96.3 | \n", 306 | "172.4 | \n", 307 | "65.4 | \n", 308 | "51.6 | \n", 309 | "2365 | \n", 310 | "2bbl | \n", 311 | "25 | \n", 312 | "32 | \n", 313 | "6989 | \n", 314 | "
| 11 | \n", 317 | "Honda11 | \n", 318 | "gas | \n", 319 | "std | \n", 320 | "two | \n", 321 | "fwd | \n", 322 | "86.6 | \n", 323 | "144.6 | \n", 324 | "63.9 | \n", 325 | "50.8 | \n", 326 | "1713 | \n", 327 | "1bbl | \n", 328 | "49 | \n", 329 | "54 | \n", 330 | "6479 | \n", 331 | "
| \n", 409 | " | classname | \n", 410 | "engine_location | \n", 411 | "engine_type | \n", 412 | "num_of_cylinders | \n", 413 | "engine_size | \n", 414 | "bore | \n", 415 | "stroke | \n", 416 | "compression_ratio | \n", 417 | "horse_power | \n", 418 | "peak_rpm | \n", 419 | "
|---|---|---|---|---|---|---|---|---|---|---|
| 13 | \n", 424 | "Wagon13 | \n", 425 | "front | \n", 426 | "ohc | \n", 427 | "four | \n", 428 | "92 | \n", 429 | "2.92 | \n", 430 | "3.41 | \n", 431 | "9.2 | \n", 432 | "76 | \n", 433 | "6000 | \n", 434 | "
| 9 | \n", 437 | "Sedan9 | \n", 438 | "front | \n", 439 | "ohc | \n", 440 | "four | \n", 441 | "90 | \n", 442 | "2.97 | \n", 443 | "3.23 | \n", 444 | "9.4 | \n", 445 | "68 | \n", 446 | "5500 | \n", 447 | "
| 16 | \n", 450 | "Sedan16 | \n", 451 | "front | \n", 452 | "dohc | \n", 453 | "six | \n", 454 | "258 | \n", 455 | "3.63 | \n", 456 | "4.17 | \n", 457 | "8.1 | \n", 458 | "176 | \n", 459 | "4750 | \n", 460 | "
| 5 | \n", 463 | "Sedan5 | \n", 464 | "front | \n", 465 | "ohc | \n", 466 | "four | \n", 467 | "108 | \n", 468 | "3.5 | \n", 469 | "2.8 | \n", 470 | "8.8 | \n", 471 | "101 | \n", 472 | "5800 | \n", 473 | "
| 18 | \n", 476 | "Sedan18 | \n", 477 | "front | \n", 478 | "ohc | \n", 479 | "four | \n", 480 | "91 | \n", 481 | "3.03 | \n", 482 | "3.15 | \n", 483 | "9.0 | \n", 484 | "68 | \n", 485 | "5000 | \n", 486 | "
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 |
--------------------------------------------------------------------------------