{ "cells": [ { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "# Foundations of Computational Economics #7\n", "\n", "by Fedor Iskhakov, ANU\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "fragment" } }, "source": [ "## Python essentials: object-oriented programming\n", "\n", "" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "subslide" } }, "source": [ "\n", "\n", "[https://youtu.be/mwplVDkfVU0](https://youtu.be/mwplVDkfVU0)\n", "\n", "Description: Classes and objects. Attributes, properties. Encapsulation, inheritance and polymorphism." ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Styles of programming languges\n", "\n", "- **Procedural programming** \n", " - Series of computational steps to be carried out \n", " - Routines/functions for modularization of steps \n", "- **Functional programming** \n", " - programming with expressions or declarations instead of statements \n", "- **Object-oriented programming** \n", " - classes and objects with attributes/properties and methods \n", "\n", "\n", "Python is a pragmatic mix of styles" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Procedural programming" ] }, { "cell_type": "code", "execution_count": 1, "metadata": { "hide-output": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 1 2 3 5 8 13 21 34 55 " ] } ], "source": [ "def fibonacci_procedural(n, fst=1, sec=1):\n", " ''' Return the Fibonacci sequence up to n as a list'''\n", " f = [0]*n # list of n zeros\n", " f[0],f[1] = fst, sec\n", " for i in range(2,n):\n", " f[i] = f[i-1] + f[i-2]\n", " return f\n", "\n", "x1, x2 = 1,1 # data stored outside\n", "for k in fibonacci_procedural(10,x1,x2):\n", " print(k,end=' ') # print without new line" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Functional programming" ] }, { "cell_type": "code", "execution_count": 2, "metadata": { "hide-output": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 1 2 3 5 8 13 21 34 55 " ] } ], "source": [ "# Returns Fibonacci sequence up to n as a list\n", "fibonacci_functional = (lambda n, first=1, second=1:\n", " [] if n == 0 else\n", " [first] + fibonacci_functional(n - 1, second, first + second))\n", "\n", "for k in fibonacci_functional(10):\n", " print(k,end=' ')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### fibonacci_functional()\n", "\n", "- Lambda function of 3 arguments, last two are optional and defaulted to 1 \n", "- If $ n=0 $ returns empty list \n", "- If $ n>0 $ proceed as follows: \n", " \n", " - calls itself with decremented step counter and updated arguments \n", " - appends the returned list to the [first] \n", " \n", "- Altogether $ n $ recursive calls \n", " \n", " - counting steps down from the initial $ n $ to 0 \n", " - returning growing list of Fibonacci numbers " ] }, { "cell_type": "code", "execution_count": 3, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "...........1 1 2 3 5 8 13 21 34 55 " ] } ], "source": [ "# Count how many times the function is actually called\n", "\n", "fibonacci_functional = (lambda n, first=1, second=1:\n", " print('.',end='') or (\n", " [] if n == 0 else\n", " [first] + fibonacci_functional(n - 1, second, first + second)))\n", "\n", "for k in fibonacci_functional(10):\n", " print(k,end=' ')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Object-oriented programming" ] }, { "cell_type": "code", "execution_count": 4, "metadata": { "hide-output": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "\n", "1 1 2 3 5 8 13 21 34 55 " ] } ], "source": [ "class fibonacci:\n", " ''' Builds Fibonacci sequence up to n as a list'''\n", " fst = 1 # data stored inside\n", " sec = 1 # static attributes = the same for all objects\n", "\n", " def __init__(self,n=5): # initializer/constructor\n", " self.n = n # public attribute\n", "\n", " def __call__(self): # method to make object callable\n", " f = [0]*self.n # list of n zeros\n", " f[0],f[1] = fibonacci.fst, fibonacci.sec\n", " for i in range(2,self.n):\n", " f[i] = f[i-1] + f[i-2]\n", " return f\n", "\n", "f = fibonacci(10) # instance of a class = object\n", "print(type(f))\n", "for k in f(): # call object fibonacci directly to get the list\n", " print(k,end=' ') # print without new line" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Object-oriented programming (OOP)\n", "\n", "- Classes \n", "- Objects \n", "- Attributes/properties \n", "- Methods " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### OOP principles\n", "\n", "- **Encapsulation** and **Abstraction** = Combining functions\n", " and related data withing the object, and exposing only needed interface\n", " while hiding internal mechanism for independent code refactoring \n", "- **Inheritance** = class hierarchies $ \\leftrightarrow $ inhereted\n", " methods don’t have to be re-implemented, although can be replaced/overloaded \n", "- **Polymorphism** = same functions/interfaces for different types\n", " $ \\leftrightarrow $ classes have methods with same names " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Function to explore the class/object structure" ] }, { "cell_type": "code", "execution_count": 5, "metadata": { "hide-output": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Writing obj_explore.py\n" ] } ], "source": [ "%%writefile 'obj_explore.py'\n", "\n", "def obj_explore(obj,what='all'):\n", " '''Lists attributes and methods of a class\n", " Input arguments: obj = variable to explore,\n", " what = string with any combination of\n", " all, public, private, methods, properties\n", " '''\n", " import sys # this function will run rarely, so import here\n", " trstr = lambda s: s[:30] if isinstance(s, str) else s # truncates if string\n", " spacer = lambda s: \" \"*max(15-len(s),2) # returns spacer to pad strings\n", " hr='-'*60 # horizontal line\n", " print(obj) # string representation of the input\n", " print('%s\\nObject report on object = %r' % (hr,obj))\n", " cl=type(obj)\n", " print('Objec class : %s' % cl)\n", " print('Parent classes : %r' % cl.__bases__)\n", " print('Occupied memory : %d bytes' % sys.getsizeof(obj))\n", " if what in 'all public properties':\n", " print('PUBLIC PROPERTIES')\n", " data = [(name,getattr(obj,name)) for name in dir(obj) if not callable(getattr(obj,name)) and name[0:2]!='__']\n", " for item in data:\n", " print('%s = %r %s' % (item[0]+spacer(item[0]),trstr(item[1]),type(item[1])))\n", " if what in 'all private properties':\n", " print('PRIVATE PROPERTIES')\n", " data = [(name,getattr(obj,name)) for name in dir(obj) if not callable(getattr(obj,name)) and name[0:2]=='__']\n", " for item in data:\n", " print('%s = %r %s' % (item[0]+spacer(item[0]),trstr(item[1]),type(item[1])))\n", " if what in 'all public methods':\n", " print('PUBLIC METHODS')\n", " data = [(name,getattr(obj,name)) for name in dir(obj) if callable(getattr(obj,name)) and name[0:2]!='__']\n", " for item in data:\n", " print('%s %s' % (item[0]+spacer(item[0]),type(item[1])))\n", " if what in 'all private methods':\n", " print('PRIVATE METHODS')\n", " data = [(name,getattr(obj,name)) for name in dir(obj) if callable(getattr(obj,name)) and name[0:2]=='__']\n", " for item in data:\n", " print('%s %s' % (item[0]+spacer(item[0]),type(item[1])))" ] }, { "cell_type": "code", "execution_count": 6, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Help on function obj_explore in module obj_explore:\n", "\n", "obj_explore(obj, what='all')\n", " Lists attributes and methods of a class\n", " Input arguments: obj = variable to explore,\n", " what = string with any combination of\n", " all, public, private, methods, properties\n", "\n" ] } ], "source": [ "# import all functions from obj_explore.py\n", "from obj_explore import *\n", "help(obj_explore)" ] }, { "cell_type": "code", "execution_count": 7, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "False\n", "------------------------------------------------------------\n", "Object report on object = False\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 24 bytes\n", "PUBLIC PROPERTIES\n", "denominator = 1 \n", "imag = 0 \n", "numerator = 0 \n", "real = 0 \n", "PRIVATE PROPERTIES\n", "__doc__ = 'bool(x) -> bool\\n\\nReturns True ' \n", "PUBLIC METHODS\n", "bit_length \n", "conjugate \n", "from_bytes \n", "to_bytes \n", "PRIVATE METHODS\n", "__abs__ \n", "__add__ \n", "__and__ \n", "__bool__ \n", "__ceil__ \n", "__class__ \n", "__delattr__ \n", "__dir__ \n", "__divmod__ \n", "__eq__ \n", "__float__ \n", "__floor__ \n", "__floordiv__ \n", "__format__ \n", "__ge__ \n", "__getattribute__ \n", "__getnewargs__ \n", "__gt__ \n", "__hash__ \n", "__index__ \n", "__init__ \n", "__init_subclass__ \n", "__int__ \n", "__invert__ \n", "__le__ \n", "__lshift__ \n", "__lt__ \n", "__mod__ \n", "__mul__ \n", "__ne__ \n", "__neg__ \n", "__new__ \n", "__or__ \n", "__pos__ \n", "__pow__ \n", "__radd__ \n", "__rand__ \n", "__rdivmod__ \n", "__reduce__ \n", "__reduce_ex__ \n", "__repr__ \n", "__rfloordiv__ \n", "__rlshift__ \n", "__rmod__ \n", "__rmul__ \n", "__ror__ \n", "__round__ \n", "__rpow__ \n", "__rrshift__ \n", "__rshift__ \n", "__rsub__ \n", "__rtruediv__ \n", "__rxor__ \n", "__setattr__ \n", "__sizeof__ \n", "__str__ \n", "__sub__ \n", "__subclasshook__ \n", "__truediv__ \n", "__trunc__ \n", "__xor__ \n" ] } ], "source": [ "x = False # Boolean\n", "obj_explore(x)" ] }, { "cell_type": "code", "execution_count": 8, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "10\n", "------------------------------------------------------------\n", "Object report on object = 10\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 28 bytes\n", "PUBLIC PROPERTIES\n", "denominator = 1 \n", "imag = 0 \n", "numerator = 10 \n", "real = 10 \n", "PRIVATE PROPERTIES\n", "__doc__ = 'int([x]) -> integer\\nint(x, bas' \n", "PUBLIC METHODS\n", "bit_length \n", "conjugate \n", "from_bytes \n", "to_bytes \n", "PRIVATE METHODS\n", "__abs__ \n", "__add__ \n", "__and__ \n", "__bool__ \n", "__ceil__ \n", "__class__ \n", "__delattr__ \n", "__dir__ \n", "__divmod__ \n", "__eq__ \n", "__float__ \n", "__floor__ \n", "__floordiv__ \n", "__format__ \n", "__ge__ \n", "__getattribute__ \n", "__getnewargs__ \n", "__gt__ \n", "__hash__ \n", "__index__ \n", "__init__ \n", "__init_subclass__ \n", "__int__ \n", "__invert__ \n", "__le__ \n", "__lshift__ \n", "__lt__ \n", "__mod__ \n", "__mul__ \n", "__ne__ \n", "__neg__ \n", "__new__ \n", "__or__ \n", "__pos__ \n", "__pow__ \n", "__radd__ \n", "__rand__ \n", "__rdivmod__ \n", "__reduce__ \n", "__reduce_ex__ \n", "__repr__ \n", "__rfloordiv__ \n", "__rlshift__ \n", "__rmod__ \n", "__rmul__ \n", "__ror__ \n", "__round__ \n", "__rpow__ \n", "__rrshift__ \n", "__rshift__ \n", "__rsub__ \n", "__rtruediv__ \n", "__rxor__ \n", "__setattr__ \n", "__sizeof__ \n", "__str__ \n", "__sub__ \n", "__subclasshook__ \n", "__truediv__ \n", "__trunc__ \n", "__xor__ \n" ] } ], "source": [ "x = 0b1010 # Integer\n", "obj_explore(x)" ] }, { "cell_type": "code", "execution_count": 9, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "4.32913\n", "------------------------------------------------------------\n", "Object report on object = 4.32913\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 24 bytes\n", "PUBLIC PROPERTIES\n", "imag = 0.0 \n", "real = 4.32913 \n", "PRIVATE PROPERTIES\n", "__doc__ = 'Convert a string or number to ' \n", "PUBLIC METHODS\n", "as_integer_ratio \n", "conjugate \n", "fromhex \n", "hex \n", "is_integer \n", "PRIVATE METHODS\n", "__abs__ \n", "__add__ \n", "__bool__ \n", "__class__ \n", "__delattr__ \n", "__dir__ \n", "__divmod__ \n", "__eq__ \n", "__float__ \n", "__floordiv__ \n", "__format__ \n", "__ge__ \n", "__getattribute__ \n", "__getformat__ \n", "__getnewargs__ \n", "__gt__ \n", "__hash__ \n", "__init__ \n", "__init_subclass__ \n", "__int__ \n", "__le__ \n", "__lt__ \n", "__mod__ \n", "__mul__ \n", "__ne__ \n", "__neg__ \n", "__new__ \n", "__pos__ \n", "__pow__ \n", "__radd__ \n", "__rdivmod__ \n", "__reduce__ \n", "__reduce_ex__ \n", "__repr__ \n", "__rfloordiv__ \n", "__rmod__ \n", "__rmul__ \n", "__round__ \n", "__rpow__ \n", "__rsub__ \n", "__rtruediv__ \n", "__set_format__ \n", "__setattr__ \n", "__sizeof__ \n", "__str__ \n", "__sub__ \n", "__subclasshook__ \n", "__truediv__ \n", "__trunc__ \n" ] } ], "source": [ "x = 4.32913 # Float\n", "obj_explore(x)" ] }, { "cell_type": "code", "execution_count": 10, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Australian National University\n", "------------------------------------------------------------\n", "Object report on object = 'Australian National University'\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 79 bytes\n", "PUBLIC METHODS\n", "capitalize \n", "casefold \n", "center \n", "count \n", "encode \n", "endswith \n", "expandtabs \n", "find \n", "format \n", "format_map \n", "index \n", "isalnum \n", "isalpha \n", "isascii \n", "isdecimal \n", "isdigit \n", "isidentifier \n", "islower \n", "isnumeric \n", "isprintable \n", "isspace \n", "istitle \n", "isupper \n", "join \n", "ljust \n", "lower \n", "lstrip \n", "maketrans \n", "partition \n", "replace \n", "rfind \n", "rindex \n", "rjust \n", "rpartition \n", "rsplit \n", "rstrip \n", "split \n", "splitlines \n", "startswith \n", "strip \n", "swapcase \n", "title \n", "translate \n", "upper \n", "zfill \n" ] } ], "source": [ "x = \"Australian National University\" # String\n", "obj_explore(x,'public methods')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Polymorphism for strings\n", "\n", "- $ == $ (quality) $ \\rightarrow $ True/False \n", "- $ + $ (addition) $ \\rightarrow $ concatenation \n", "- $ - $ (subtraction) undefined \n", "- $ * $ (multiplication) $ \\rightarrow $ repetition (int) \n", "- $ / $ (devision) undefined \n", "- $ < > \\le \\ge $ (comparison ) $ \\rightarrow $ lexicographical\n", " comparison based on ASCII codes " ] }, { "cell_type": "code", "execution_count": 11, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "data": { "text/plain": [ "'Economics Econometrics '" ] }, "execution_count": 11, "metadata": {}, "output_type": "execute_result" } ], "source": [ "s1 = \"Economics \"\n", "s2 = \"Econometrics \"\n", "s1 + s2\n", "# s1+2\n", "# s1+str(2)\n", "# (s1+s2)*2\n", "# (s1+s2)*2 == s1*2 + s2*2" ] }, { "cell_type": "code", "execution_count": 12, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "[4, 5, 'hello']\n", "------------------------------------------------------------\n", "Object report on object = [4, 5, 'hello']\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 96 bytes\n", "PUBLIC PROPERTIES\n", "PUBLIC METHODS\n", "append \n", "clear \n", "copy \n", "count \n", "extend \n", "index \n", "insert \n", "pop \n", "remove \n", "reverse \n", "sort \n" ] } ], "source": [ "x = [4,5,'hello'] # List\n", "obj_explore(x,'public')" ] }, { "cell_type": "code", "execution_count": 13, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "(4, 5, 'hello')\n", "------------------------------------------------------------\n", "Object report on object = (4, 5, 'hello')\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 80 bytes\n", "PUBLIC PROPERTIES\n", "PUBLIC METHODS\n", "count \n", "index \n" ] } ], "source": [ "x = (4,5,'hello') # Tuple => immutable\n", "obj_explore(x,'public')" ] }, { "cell_type": "code", "execution_count": 14, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "{'key': 'value', 'another_key': 574}\n", "------------------------------------------------------------\n", "Object report on object = {'key': 'value', 'another_key': 574}\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 248 bytes\n", "PUBLIC PROPERTIES\n", "PRIVATE PROPERTIES\n", "__doc__ = 'dict() -> new empty dictionary' \n", "__hash__ = None \n", "PUBLIC METHODS\n", "clear \n", "copy \n", "fromkeys \n", "get \n", "items \n", "keys \n", "pop \n", "popitem \n", "setdefault \n", "update \n", "values \n", "PRIVATE METHODS\n", "__class__ \n", "__contains__ \n", "__delattr__ \n", "__delitem__ \n", "__dir__ \n", "__eq__ \n", "__format__ \n", "__ge__ \n", "__getattribute__ \n", "__getitem__ \n", "__gt__ \n", "__init__ \n", "__init_subclass__ \n", "__iter__ \n", "__le__ \n", "__len__ \n", "__lt__ \n", "__ne__ \n", "__new__ \n", "__reduce__ \n", "__reduce_ex__ \n", "__repr__ \n", "__setattr__ \n", "__setitem__ \n", "__sizeof__ \n", "__str__ \n", "__subclasshook__ \n" ] } ], "source": [ "x = {\"key\": \"value\",\"another_key\": 574} # Dictionary\n", "obj_explore(x)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Inheritance for booleans\n", "\n", "By-default copy of all methods and properties" ] }, { "cell_type": "code", "execution_count": 15, "metadata": { "hide-output": false, "slideshow": { "slide_type": "fragment" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Own class : \n", "Parent class: \n" ] } ], "source": [ "x=True\n", "cl=type(x)\n", "print(\"Own class : %s\" % cl) # list of parent classes\n", "print(\"Parent class: %s\" % cl.__bases__) # list of parent classes" ] }, { "cell_type": "code", "execution_count": 16, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ " at 0x7f85c8281440>\n", "------------------------------------------------------------\n", "Object report on object = at 0x7f85c8281440>\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 144 bytes\n", "PUBLIC METHODS\n", "PRIVATE METHODS\n", "__call__ \n", "__class__ \n", "__delattr__ \n", "__dir__ \n", "__eq__ \n", "__format__ \n", "__ge__ \n", "__get__ \n", "__getattribute__ \n", "__gt__ \n", "__hash__ \n", "__init__ \n", "__init_subclass__ \n", "__le__ \n", "__lt__ \n", "__ne__ \n", "__new__ \n", "__reduce__ \n", "__reduce_ex__ \n", "__repr__ \n", "__setattr__ \n", "__sizeof__ \n", "__str__ \n", "__subclasshook__ \n" ] } ], "source": [ "f = lambda x: x # identity lambda-function\n", "obj_explore(f,'methods')" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "#### Everything in Python is an object!\n", "\n", "- Variables of all types \n", "- Functions, both custom and inbuilt \n", "- Imported modules \n", "- Input and output (files) \n", "- etc. " ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### How to write classes\n", "\n", "1. When do I need a class/object? \n", " - collection of model parameters \n", " - repeatedly used complex *things* \n", " - note: collection of functions is **module** = .py file with defs \n", "1. Syntax \n", "\n", "\n", "List of standard methods:\n", "[https://docs.python.org/3/reference/datamodel.html#special-method-names](https://docs.python.org/3/reference/datamodel.html#special-method-names)" ] }, { "cell_type": "code", "execution_count": 17, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "class Firm:\n", " '''Stores the parameters of the production function f(k) = Ak^α,\n", " implements the function.\n", " '''\n", " def __init__(self, α=0.5, A=2.0): # initializer\n", " self.α = α # Public properties\n", " self.A = A\n", "\n", " def production(self, val): # public method\n", " return self.A * val**self.α" ] }, { "cell_type": "code", "execution_count": 18, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "<__main__.Firm object at 0x7f85e8a34850>\n", "------------------------------------------------------------\n", "Object report on object = <__main__.Firm object at 0x7f85e8a34850>\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 64 bytes\n", "PUBLIC PROPERTIES\n", "A = 2.0 \n", "α = 0.5 \n", "PRIVATE PROPERTIES\n", "__dict__ = {'α': 0.5, 'A': 2.0} \n", "__doc__ = 'Stores the parameters of the p' \n", "__module__ = '__main__' \n", "__weakref__ = None \n", "PUBLIC METHODS\n", "production \n", "PRIVATE METHODS\n", "__class__ \n", "__delattr__ \n", "__dir__ \n", "__eq__ \n", "__format__ \n", "__ge__ \n", "__getattribute__ \n", "__gt__ \n", "__hash__ \n", "__init__ \n", "__init_subclass__ \n", "__le__ \n", "__lt__ \n", "__ne__ \n", "__new__ \n", "__reduce__ \n", "__reduce_ex__ \n", "__repr__ \n", "__setattr__ \n", "__sizeof__ \n", "__str__ \n", "__subclasshook__ \n", "6.324555320336759\n", "9.486832980505138\n", "12.649110640673518\n" ] } ], "source": [ "firm1 = Firm()\n", "obj_explore(firm1)\n", "firm2 = Firm(A=3.0)\n", "firm3 = Firm(A=4.0)\n", "\n", "# firm1.α\n", "k = 10.0\n", "print(firm1.production(k))\n", "print(firm2.production(k))\n", "print(firm3.production(k))" ] }, { "cell_type": "code", "execution_count": 19, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [], "source": [ "class Polynomial():\n", " ''' Class to implement polynomial objects and binary operations on polynomialss\n", " '''\n", "\n", " def __init__(self, coeffs=[0,]): # Initialization\n", " # Public properties\n", " self.degree = len(coeffs) - 1\n", " self.rep = self.str(coeffs)\n", " self.coefficients = coeffs\n", "\n", " def __repr__(self):\n", " # Screen reprentation\n", " return self.rep\n", "\n", " def str(self, coeffs):\n", " # Create list of nonzero terms\n", " terms = [str(coeffs[k]) + 'x^' + str(k) for k in range(0, self.degree + 1) if coeffs[k] != 0]\n", " # If zero polynomial, return 0\n", " if len(terms) == 0:\n", " return str(0)\n", " # Replace 0 and 1 powers\n", " if coeffs[0]!=0:\n", " terms[0] = str(coeffs[0])\n", " if len(coeffs)>1 and coeffs[1]!=0:\n", " terms[1] = str(coeffs[1]) + 'x'\n", " # Finally, concatenate terms using +\n", " return ' + '.join(terms)\n", "\n", " def __add__(self, other):\n", " '''Overloads the + operator.'''\n", " d = max(self.degree, other.degree) + 1 # max length of polynomials' coeff lists\n", " self_temp = self.coefficients + [0]*(d-self.degree-1) # pad coeffs lists with 0s until equal length\n", " other_temp = other.coefficients + [0]*(d-other.degree-1)\n", " new_temp = [self_temp[i] + other_temp[i] for i in range(d)] # sum coeffs lists elementwise\n", " return Polynomial(new_temp) # return NEW polynomial\n", "\n", " def __mul__(self, other):\n", " '''Overloads the * operator.'''\n", " n = self.degree + other.degree # degree of the product\n", " prod_coeffs = [0]*(n+1) # initalize coefficient list of product\n", " for i in range(0, self.degree + 1): # compute product\n", " for j in range(0, other.degree + 1):\n", " prod_coeffs[i+j] += self.coefficients[i] * other.coefficients[j]\n", " return Polynomial(prod_coeffs) # return NEW polynomial\n", "\n", " def __call__(self, val):\n", " '''Evaluates the polynomial at x = val.'''\n", " res=self.coefficients[0]\n", " x=val\n", " for i in range(self.degree): # using the loop avoid power calculation!\n", " res += x*self.coefficients[i+1]\n", " x*=val\n", " return res" ] }, { "cell_type": "code", "execution_count": 20, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "1 + 2x + 3x^2\n", "------------------------------------------------------------\n", "Object report on object = 1 + 2x + 3x^2\n", "Objec class : \n", "Parent classes : \n", "Occupied memory : 64 bytes\n", "PUBLIC PROPERTIES\n", "coefficients = [1, 2, 3] \n", "degree = 2 \n", "rep = '1 + 2x + 3x^2' \n", "PUBLIC METHODS\n", "str \n" ] } ], "source": [ "p=Polynomial([1,2,3])\n", "obj_explore(p,'public')" ] }, { "cell_type": "code", "execution_count": 21, "metadata": { "hide-output": false, "slideshow": { "slide_type": "slide" } }, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "p1(x) = 1 + 2x + 5x^2 + 4x^5\n", "p1(5) = 12636\n", "p2 = 10 + 3x^2 + 7x^3\n", "p2(2) = 78\n", "Sum 11 + 2x + 8x^2 + 7x^3 + 4x^5\n", "Product 10 + 20x + 53x^2 + 13x^3 + 29x^4 + 75x^5 + 12x^7 + 28x^8\n" ] } ], "source": [ "p1=Polynomial([1,2,5,0,0,4])\n", "print('p1(x) = %r' % p1)\n", "print('p1(5) = %r' % p1(5))\n", "p2=Polynomial([10,0,3,7])\n", "print('p2 = %r' % p2)\n", "print('p2(2) = %r' % p2(2))\n", "\n", "p3=p1+p2\n", "print('Sum %r' % p3)\n", "p3=p1*p2\n", "print('Product %r' % p3)" ] }, { "cell_type": "markdown", "metadata": { "slideshow": { "slide_type": "slide" } }, "source": [ "### Further learning resources\n", "\n", "- Simple explanation to main concepts of OOP\n", " [https://www.youtube.com/watch?v=pTB0EiLXUC8](https://www.youtube.com/watch?v=pTB0EiLXUC8) \n", "- List of standard methods of Python class\n", " [https://docs.python.org/3/reference/datamodel.html#special-method-names](https://docs.python.org/3/reference/datamodel.html#special-method-names) " ] } ], "metadata": { "celltoolbar": "Slideshow", "date": 1612589584.526922, "download_nb": false, "filename": "07_pthon_obj.rst", "filename_with_path": "07_pthon_obj", "kernelspec": { "display_name": "Python", "language": "python3", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.6" }, "title": "Foundations of Computational Economics #7" }, "nbformat": 4, "nbformat_minor": 4 }