{ "cells": [ { "cell_type": "markdown", "id": "744fca70", "metadata": {}, "source": [ "\n", "\n", "
\n", " \n", " \"QuantEcon\"\n", " \n", "
" ] }, { "cell_type": "markdown", "id": "c004ef4e", "metadata": {}, "source": [ "# OOP II: Building Classes\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "eadd4a42", "metadata": {}, "source": [ "## Contents\n", "\n", "- [OOP II: Building Classes](#OOP-II:-Building-Classes) \n", " - [Overview](#Overview) \n", " - [OOP Review](#OOP-Review) \n", " - [Defining Your Own Classes](#Defining-Your-Own-Classes) \n", " - [Special Methods](#Special-Methods) \n", " - [Exercises](#Exercises) " ] }, { "cell_type": "markdown", "id": "0dd52cda", "metadata": {}, "source": [ "## Overview\n", "\n", "In an [earlier lecture](https://python-programming.quantecon.org/oop_intro.html), we learned some foundations of object-oriented programming.\n", "\n", "The objectives of this lecture are\n", "\n", "- cover OOP in more depth \n", "- learn how to build our own objects, specialized to our needs \n", "\n", "\n", "For example, you already know how to\n", "\n", "- create lists, strings and other Python objects \n", "- use their methods to modify their contents \n", "\n", "\n", "So imagine now you want to write a program with consumers, who can\n", "\n", "- hold and spend cash \n", "- consume goods \n", "- work and earn cash \n", "\n", "\n", "A natural solution in Python would be to create consumers as objects with\n", "\n", "- data, such as cash on hand \n", "- methods, such as `buy` or `work` that affect this data \n", "\n", "\n", "Python makes it easy to do this, by providing you with **class definitions**.\n", "\n", "Classes are blueprints that help you build objects according to your own specifications.\n", "\n", "It takes a little while to get used to the syntax so we’ll provide plenty of examples.\n", "\n", "We’ll use the following imports:" ] }, { "cell_type": "code", "execution_count": null, "id": "00a2e2b1", "metadata": { "hide-output": false }, "outputs": [], "source": [ "%matplotlib inline\n", "import numpy as np\n", "import matplotlib.pyplot as plt\n", "plt.rcParams['figure.figsize'] = (10,6)" ] }, { "cell_type": "markdown", "id": "a3ecdf2b", "metadata": {}, "source": [ "## OOP Review\n", "\n", "OOP is supported in many languages:\n", "\n", "- JAVA and Ruby are relatively pure OOP. \n", "- Python supports both procedural and object-oriented programming. \n", "- Fortran and MATLAB are mainly procedural, some OOP recently tacked on. \n", "- C is a procedural language, while C++ is C with OOP added on top. \n", "\n", "\n", "Let’s cover general OOP concepts before we specialize to Python." ] }, { "cell_type": "markdown", "id": "bf89e012", "metadata": {}, "source": [ "### Key Concepts\n", "\n", "\n", "\n", "As discussed an [earlier lecture](https://python-programming.quantecon.org/oop_intro.html), in the OOP paradigm, data and functions are **bundled together** into “objects”.\n", "\n", "An example is a Python list, which not only stores data but also knows how to sort itself, etc." ] }, { "cell_type": "code", "execution_count": null, "id": "05325fe1", "metadata": { "hide-output": false }, "outputs": [], "source": [ "x = [1, 5, 4]\n", "x.sort()\n", "x" ] }, { "cell_type": "markdown", "id": "1780b502", "metadata": {}, "source": [ "As we now know, `sort` is a function that is “part of” the list object — and hence called a *method*.\n", "\n", "If we want to make our own types of objects we need to use class definitions.\n", "\n", "A *class definition* is a blueprint for a particular class of objects (e.g., lists, strings or complex numbers).\n", "\n", "It describes\n", "\n", "- What kind of data the class stores \n", "- What methods it has for acting on these data \n", "\n", "\n", "An *object* or *instance* is a realization of the class, created from the blueprint\n", "\n", "- Each instance has its own unique data. \n", "- Methods set out in the class definition act on this (and other) data. \n", "\n", "\n", "In Python, the data and methods of an object are collectively referred to as *attributes*.\n", "\n", "Attributes are accessed via “dotted attribute notation”\n", "\n", "- `object_name.data` \n", "- `object_name.method_name()` \n", "\n", "\n", "In the example" ] }, { "cell_type": "code", "execution_count": null, "id": "af95387b", "metadata": { "hide-output": false }, "outputs": [], "source": [ "x = [1, 5, 4]\n", "x.sort()\n", "x.__class__" ] }, { "cell_type": "markdown", "id": "6bf060a4", "metadata": {}, "source": [ "- `x` is an object or instance, created from the definition for Python lists, but with its own particular data. \n", "- `x.sort()` and `x.__class__` are two attributes of `x`. \n", "- `dir(x)` can be used to view all the attributes of `x`. \n", "\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "94b34b70", "metadata": {}, "source": [ "### Why is OOP Useful?\n", "\n", "OOP is useful for the same reason that abstraction is useful: for recognizing and exploiting the common structure.\n", "\n", "For example,\n", "\n", "- *a Markov chain* consists of a set of states, an initial probability distribution over states, and a collection of probabilities of moving across states \n", "- *a general equilibrium theory* consists of a commodity space, preferences, technologies, and an equilibrium definition \n", "- *a game* consists of a list of players, lists of actions available to each player, each player’s payoffs as functions of all other players’ actions, and a timing protocol \n", "\n", "\n", "These are all abstractions that collect together “objects” of the same “type”.\n", "\n", "Recognizing common structure allows us to employ common tools.\n", "\n", "In economic theory, this might be a proposition that applies to all games of a certain type.\n", "\n", "In Python, this might be a method that’s useful for all Markov chains (e.g., `simulate`).\n", "\n", "When we use OOP, the `simulate` method is conveniently bundled together with the Markov chain object." ] }, { "cell_type": "markdown", "id": "ec5a228b", "metadata": {}, "source": [ "## Defining Your Own Classes\n", "\n", "\n", "\n", "Let’s build some simple classes to start off.\n", "\n", "\n", "\n", "Before we do so, in order to indicate some of the power of Classes, we’ll define two functions that we’ll call `earn` and `spend`." ] }, { "cell_type": "code", "execution_count": null, "id": "5e0313da", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def earn(w,y):\n", " \"Consumer with inital wealth w earns y\"\n", " return w+y\n", "\n", "def spend(w,x):\n", " \"consumer with initial wealth w spends x\"\n", " new_wealth = w -x\n", " if new_wealth < 0:\n", " print(\"Insufficient funds\")\n", " else:\n", " return new_wealth" ] }, { "cell_type": "markdown", "id": "9970c3c0", "metadata": {}, "source": [ "The `earn` function takes a consumer’s initial wealth $ w $ and adds to it her current earnings $ y $.\n", "\n", "The `spend` function takes a consumer’s initial wealth $ w $ and deducts from it her current spending $ x $.\n", "\n", "We can use these two functions to keep track of a consumer’s wealth as she earns and spends.\n", "\n", "For example" ] }, { "cell_type": "code", "execution_count": null, "id": "d5addd40", "metadata": { "hide-output": false }, "outputs": [], "source": [ "w0=100\n", "w1=earn(w0,10)\n", "w2=spend(w1,20)\n", "w3=earn(w2,10)\n", "w4=spend(w3,20)\n", "print(\"w0,w1,w2,w3,w4 = \", w0,w1,w2,w3,w4)" ] }, { "cell_type": "markdown", "id": "03ce6eb7", "metadata": {}, "source": [ "A *Class* bundles a set of data tied to a particular *instance* together with a collection of functions that operate on the data.\n", "\n", "In our example, an *instance* will be the name of particular *person* whose *instance data* consist solely of its wealth.\n", "\n", "(In other examples *instance data* will consist of a vector of data.)\n", "\n", "In our example, two functions `earn` and `spend` can be applied to the current instance data.\n", "\n", "Taken together, the instance data and functions are called *methods*.\n", "\n", "These can be readily accessed in ways that we shall describe now." ] }, { "cell_type": "markdown", "id": "14a21fce", "metadata": {}, "source": [ "### Example: A Consumer Class\n", "\n", "We’ll build a `Consumer` class with\n", "\n", "- a `wealth` attribute that stores the consumer’s wealth (data) \n", "- an `earn` method, where `earn(y)` increments the consumer’s wealth by `y` \n", "- a `spend` method, where `spend(x)` either decreases wealth by `x` or returns an error if insufficient funds exist \n", "\n", "\n", "Admittedly a little contrived, this example of a class helps us internalize some peculiar syntax.\n", "\n", "Here how we set up our Consumer class." ] }, { "cell_type": "code", "execution_count": null, "id": "18196b17", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class Consumer:\n", "\n", " def __init__(self, w):\n", " \"Initialize consumer with w dollars of wealth\"\n", " self.wealth = w\n", "\n", " def earn(self, y):\n", " \"The consumer earns y dollars\"\n", " self.wealth += y\n", "\n", " def spend(self, x):\n", " \"The consumer spends x dollars if feasible\"\n", " new_wealth = self.wealth - x\n", " if new_wealth < 0:\n", " print(\"Insufficent funds\")\n", " else:\n", " self.wealth = new_wealth" ] }, { "cell_type": "markdown", "id": "80508852", "metadata": {}, "source": [ "There’s some special syntax here so let’s step through carefully\n", "\n", "- The `class` keyword indicates that we are building a class. \n", "\n", "\n", "The `Consumer` class defines instance data `wealth` and three methods: `__init__`, `earn` and `spend`\n", "\n", "- `wealth` is *instance data* because each consumer we create (each instance of the `Consumer` class) will have its own wealth data. \n", "\n", "\n", "The `earn` and `spend` methods deploy the functions we described earlier and that can potentially be applied to the `wealth` instance data.\n", "\n", "The `__init__` method is a *constructor method*.\n", "\n", "Whenever we create an instance of the class, the `__init_` method will be called automatically.\n", "\n", "Calling `__init__` sets up a “namespace” to hold the instance data — more on this soon.\n", "\n", "We’ll also discuss the role of the peculiar `self` bookkeeping device in detail below." ] }, { "cell_type": "markdown", "id": "abd3c7a0", "metadata": {}, "source": [ "#### Usage\n", "\n", "Here’s an example in which we use the class `Consumer` to create an instance of a consumer whom we affectionately name $ c1 $.\n", "\n", "After we create consumer $ c1 $ and endow it with initial wealth $ 10 $, we’ll apply the `spend` method." ] }, { "cell_type": "code", "execution_count": null, "id": "3791ca35", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c1 = Consumer(10) # Create instance with initial wealth 10\n", "c1.spend(5)\n", "c1.wealth" ] }, { "cell_type": "code", "execution_count": null, "id": "d55155d7", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c1.earn(15)\n", "c1.spend(100)" ] }, { "cell_type": "markdown", "id": "eab2ff41", "metadata": {}, "source": [ "We can of course create multiple instances, i.e., multiple consumers, each with its own name and data" ] }, { "cell_type": "code", "execution_count": null, "id": "15d9255b", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c1 = Consumer(10)\n", "c2 = Consumer(12)\n", "c2.spend(4)\n", "c2.wealth" ] }, { "cell_type": "code", "execution_count": null, "id": "c755a70c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c1.wealth" ] }, { "cell_type": "markdown", "id": "2199a23e", "metadata": {}, "source": [ "Each instance, i.e., each consumer, stores its data in a separate namespace dictionary" ] }, { "cell_type": "code", "execution_count": null, "id": "e14e4d0e", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c1.__dict__" ] }, { "cell_type": "code", "execution_count": null, "id": "523b60cb", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c2.__dict__" ] }, { "cell_type": "markdown", "id": "4eb4a3a6", "metadata": {}, "source": [ "When we access or set attributes we’re actually just modifying the dictionary\n", "maintained by the instance." ] }, { "cell_type": "markdown", "id": "c4090009", "metadata": {}, "source": [ "#### Self\n", "\n", "If you look at the `Consumer` class definition again you’ll see the word\n", "self throughout the code.\n", "\n", "The rules for using `self` in creating a Class are that\n", "\n", "- Any instance data should be prepended with `self` \n", " - e.g., the `earn` method uses `self.wealth` rather than just `wealth` \n", "- A method defined within the code that defines the class should have `self` as its first argument \n", " - e.g., `def earn(self, y)` rather than just `def earn(y)` \n", "- Any method referenced within the class should be called as `self.method_name` \n", "\n", "\n", "There are no examples of the last rule in the preceding code but we will see some shortly." ] }, { "cell_type": "markdown", "id": "fea48623", "metadata": {}, "source": [ "#### Details\n", "\n", "In this section, we look at some more formal details related to classes and `self`\n", "\n", "- You might wish to skip to [the next section](#oop-solow-growth) the first time you read this lecture. \n", "- You can return to these details after you’ve familiarized yourself with more examples. \n", "\n", "\n", "Methods actually live inside a class object formed when the interpreter reads\n", "the class definition" ] }, { "cell_type": "code", "execution_count": null, "id": "c892fa3f", "metadata": { "hide-output": false }, "outputs": [], "source": [ "print(Consumer.__dict__) # Show __dict__ attribute of class object" ] }, { "cell_type": "markdown", "id": "e5ed6eb9", "metadata": {}, "source": [ "Note how the three methods `__init__`, `earn` and `spend` are stored in the class object.\n", "\n", "Consider the following code" ] }, { "cell_type": "code", "execution_count": null, "id": "4f1f1073", "metadata": { "hide-output": false }, "outputs": [], "source": [ "c1 = Consumer(10)\n", "c1.earn(10)\n", "c1.wealth" ] }, { "cell_type": "markdown", "id": "1330a891", "metadata": {}, "source": [ "When you call `earn` via `c1.earn(10)` the interpreter passes the instance `c1` and the argument `10` to `Consumer.earn`.\n", "\n", "In fact, the following are equivalent\n", "\n", "- `c1.earn(10)` \n", "- `Consumer.earn(c1, 10)` \n", "\n", "\n", "In the function call `Consumer.earn(c1, 10)` note that `c1` is the first argument.\n", "\n", "Recall that in the definition of the `earn` method, `self` is the first parameter" ] }, { "cell_type": "code", "execution_count": null, "id": "cce95731", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def earn(self, y):\n", " \"The consumer earns y dollars\"\n", " self.wealth += y" ] }, { "cell_type": "markdown", "id": "bfd66d05", "metadata": {}, "source": [ "The end result is that `self` is bound to the instance `c1` inside the function call.\n", "\n", "That’s why the statement `self.wealth += y` inside `earn` ends up modifying `c1.wealth`.\n", "\n", "\n", "" ] }, { "cell_type": "markdown", "id": "916d4ed6", "metadata": {}, "source": [ "### Example: The Solow Growth Model\n", "\n", "\n", "\n", "For our next example, let’s write a simple class to implement the Solow growth model.\n", "\n", "The Solow growth model is a neoclassical growth model in which the per capita\n", "capital stock $ k_t $ evolves according to the rule\n", "\n", "\n", "\n", "$$\n", "k_{t+1} = \\frac{s z k_t^{\\alpha} + (1 - \\delta) k_t}{1 + n} \\tag{8.1}\n", "$$\n", "\n", "Here\n", "\n", "- $ s $ is an exogenously given saving rate \n", "- $ z $ is a productivity parameter \n", "- $ \\alpha $ is capital’s share of income \n", "- $ n $ is the population growth rate \n", "- $ \\delta $ is the depreciation rate \n", "\n", "\n", "A **steady state** of the model is a $ k $ that solves [(8.1)](#equation-solow-lom) when $ k_{t+1} = k_t = k $.\n", "\n", "Here’s a class that implements this model.\n", "\n", "Some points of interest in the code are\n", "\n", "- An instance maintains a record of its current capital stock in the variable `self.k`. \n", "- The `h` method implements the right-hand side of [(8.1)](#equation-solow-lom). \n", "- The `update` method uses `h` to update capital as per [(8.1)](#equation-solow-lom). \n", " - Notice how inside `update` the reference to the local method `h` is `self.h`. \n", "\n", "\n", "The methods `steady_state` and `generate_sequence` are fairly self-explanatory" ] }, { "cell_type": "code", "execution_count": null, "id": "1a36e94a", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class Solow:\n", " r\"\"\"\n", " Implements the Solow growth model with the update rule\n", "\n", " k_{t+1} = [(s z k^α_t) + (1 - δ)k_t] /(1 + n)\n", "\n", " \"\"\"\n", " def __init__(self, n=0.05, # population growth rate\n", " s=0.25, # savings rate\n", " δ=0.1, # depreciation rate\n", " α=0.3, # share of labor\n", " z=2.0, # productivity\n", " k=1.0): # current capital stock\n", "\n", " self.n, self.s, self.δ, self.α, self.z = n, s, δ, α, z\n", " self.k = k\n", "\n", " def h(self):\n", " \"Evaluate the h function\"\n", " # Unpack parameters (get rid of self to simplify notation)\n", " n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z\n", " # Apply the update rule\n", " return (s * z * self.k**α + (1 - δ) * self.k) / (1 + n)\n", "\n", " def update(self):\n", " \"Update the current state (i.e., the capital stock).\"\n", " self.k = self.h()\n", "\n", " def steady_state(self):\n", " \"Compute the steady state value of capital.\"\n", " # Unpack parameters (get rid of self to simplify notation)\n", " n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z\n", " # Compute and return steady state\n", " return ((s * z) / (n + δ))**(1 / (1 - α))\n", "\n", " def generate_sequence(self, t):\n", " \"Generate and return a time series of length t\"\n", " path = []\n", " for i in range(t):\n", " path.append(self.k)\n", " self.update()\n", " return path" ] }, { "cell_type": "markdown", "id": "8148d7a6", "metadata": {}, "source": [ "Here’s a little program that uses the class to compute time series from two different initial conditions.\n", "\n", "The common steady state is also plotted for comparison" ] }, { "cell_type": "code", "execution_count": null, "id": "f9866ec5", "metadata": { "hide-output": false }, "outputs": [], "source": [ "s1 = Solow()\n", "s2 = Solow(k=8.0)\n", "\n", "T = 60\n", "fig, ax = plt.subplots(figsize=(9, 6))\n", "\n", "# Plot the common steady state value of capital\n", "ax.plot([s1.steady_state()]*T, 'k-', label='steady state')\n", "\n", "# Plot time series for each economy\n", "for s in s1, s2:\n", " lb = f'capital series from initial state {s.k}'\n", " ax.plot(s.generate_sequence(T), 'o-', lw=2, alpha=0.6, label=lb)\n", "\n", "ax.set_xlabel('$t$', fontsize=14)\n", "ax.set_ylabel('$k_t$', fontsize=14)\n", "ax.legend()\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "9b60d529", "metadata": {}, "source": [ "### Example: A Market\n", "\n", "Next, let’s write a class for competitive market in which buyers and sellers are both price takers.\n", "\n", "The market consists of the following objects:\n", "\n", "- A linear demand curve $ Q = a_d - b_d p $ \n", "- A linear supply curve $ Q = a_z + b_z (p - t) $ \n", "\n", "\n", "Here\n", "\n", "- $ p $ is price paid by the buyer, $ Q $ is quantity and $ t $ is a per-unit tax. \n", "- Other symbols are demand and supply parameters. \n", "\n", "\n", "The class provides methods to compute various values of interest, including competitive equilibrium price and quantity, tax revenue raised, consumer surplus and producer surplus.\n", "\n", "Here’s our implementation.\n", "\n", "(It uses a function from SciPy called quad for numerical integration—a topic we will say more about later on.)" ] }, { "cell_type": "code", "execution_count": null, "id": "893dd31c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "from scipy.integrate import quad\n", "\n", "class Market:\n", "\n", " def __init__(self, ad, bd, az, bz, tax):\n", " \"\"\"\n", " Set up market parameters. All parameters are scalars. See\n", " https://lectures.quantecon.org/py/python_oop.html for interpretation.\n", "\n", " \"\"\"\n", " self.ad, self.bd, self.az, self.bz, self.tax = ad, bd, az, bz, tax\n", " if ad < az:\n", " raise ValueError('Insufficient demand.')\n", "\n", " def price(self):\n", " \"Compute equilibrium price\"\n", " return (self.ad - self.az + self.bz * self.tax) / (self.bd + self.bz)\n", "\n", " def quantity(self):\n", " \"Compute equilibrium quantity\"\n", " return self.ad - self.bd * self.price()\n", "\n", " def consumer_surp(self):\n", " \"Compute consumer surplus\"\n", " # == Compute area under inverse demand function == #\n", " integrand = lambda x: (self.ad / self.bd) - (1 / self.bd) * x\n", " area, error = quad(integrand, 0, self.quantity())\n", " return area - self.price() * self.quantity()\n", "\n", " def producer_surp(self):\n", " \"Compute producer surplus\"\n", " # == Compute area above inverse supply curve, excluding tax == #\n", " integrand = lambda x: -(self.az / self.bz) + (1 / self.bz) * x\n", " area, error = quad(integrand, 0, self.quantity())\n", " return (self.price() - self.tax) * self.quantity() - area\n", "\n", " def taxrev(self):\n", " \"Compute tax revenue\"\n", " return self.tax * self.quantity()\n", "\n", " def inverse_demand(self, x):\n", " \"Compute inverse demand\"\n", " return self.ad / self.bd - (1 / self.bd)* x\n", "\n", " def inverse_supply(self, x):\n", " \"Compute inverse supply curve\"\n", " return -(self.az / self.bz) + (1 / self.bz) * x + self.tax\n", "\n", " def inverse_supply_no_tax(self, x):\n", " \"Compute inverse supply curve without tax\"\n", " return -(self.az / self.bz) + (1 / self.bz) * x" ] }, { "cell_type": "markdown", "id": "1c5944a1", "metadata": {}, "source": [ "Here’s a sample of usage" ] }, { "cell_type": "code", "execution_count": null, "id": "f9442f4e", "metadata": { "hide-output": false }, "outputs": [], "source": [ "baseline_params = 15, .5, -2, .5, 3\n", "m = Market(*baseline_params)\n", "print(\"equilibrium price = \", m.price())" ] }, { "cell_type": "code", "execution_count": null, "id": "48c6bb91", "metadata": { "hide-output": false }, "outputs": [], "source": [ "print(\"consumer surplus = \", m.consumer_surp())" ] }, { "cell_type": "markdown", "id": "0cfa9521", "metadata": {}, "source": [ "Here’s a short program that uses this class to plot an inverse demand curve together with inverse\n", "supply curves with and without taxes" ] }, { "cell_type": "code", "execution_count": null, "id": "70571863", "metadata": { "hide-output": false }, "outputs": [], "source": [ "# Baseline ad, bd, az, bz, tax\n", "baseline_params = 15, .5, -2, .5, 3\n", "m = Market(*baseline_params)\n", "\n", "q_max = m.quantity() * 2\n", "q_grid = np.linspace(0.0, q_max, 100)\n", "pd = m.inverse_demand(q_grid)\n", "ps = m.inverse_supply(q_grid)\n", "psno = m.inverse_supply_no_tax(q_grid)\n", "\n", "fig, ax = plt.subplots()\n", "ax.plot(q_grid, pd, lw=2, alpha=0.6, label='demand')\n", "ax.plot(q_grid, ps, lw=2, alpha=0.6, label='supply')\n", "ax.plot(q_grid, psno, '--k', lw=2, alpha=0.6, label='supply without tax')\n", "ax.set_xlabel('quantity', fontsize=14)\n", "ax.set_xlim(0, q_max)\n", "ax.set_ylabel('price', fontsize=14)\n", "ax.legend(loc='lower right', frameon=False, fontsize=14)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "b16d7b35", "metadata": {}, "source": [ "The next program provides a function that\n", "\n", "- takes an instance of `Market` as a parameter \n", "- computes dead weight loss from the imposition of the tax " ] }, { "cell_type": "code", "execution_count": null, "id": "bb8a159e", "metadata": { "hide-output": false }, "outputs": [], "source": [ "def deadw(m):\n", " \"Computes deadweight loss for market m.\"\n", " # == Create analogous market with no tax == #\n", " m_no_tax = Market(m.ad, m.bd, m.az, m.bz, 0)\n", " # == Compare surplus, return difference == #\n", " surp1 = m_no_tax.consumer_surp() + m_no_tax.producer_surp()\n", " surp2 = m.consumer_surp() + m.producer_surp() + m.taxrev()\n", " return surp1 - surp2" ] }, { "cell_type": "markdown", "id": "ce66aad1", "metadata": {}, "source": [ "Here’s an example of usage" ] }, { "cell_type": "code", "execution_count": null, "id": "260ca5e6", "metadata": { "hide-output": false }, "outputs": [], "source": [ "baseline_params = 15, .5, -2, .5, 3\n", "m = Market(*baseline_params)\n", "deadw(m) # Show deadweight loss" ] }, { "cell_type": "markdown", "id": "7a92b3f9", "metadata": {}, "source": [ "### Example: Chaos\n", "\n", "Let’s look at one more example, related to chaotic dynamics in nonlinear systems.\n", "\n", "A simple transition rule that can generate erratic time paths is the logistic map\n", "\n", "\n", "\n", "$$\n", "x_{t+1} = r x_t(1 - x_t) ,\n", "\\quad x_0 \\in [0, 1],\n", "\\quad r \\in [0, 4] \\tag{8.2}\n", "$$\n", "\n", "Let’s write a class for generating time series from this model.\n", "\n", "Here’s one implementation" ] }, { "cell_type": "code", "execution_count": null, "id": "d5dd2a39", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class Chaos:\n", " \"\"\"\n", " Models the dynamical system :math:`x_{t+1} = r x_t (1 - x_t)`\n", " \"\"\"\n", " def __init__(self, x0, r):\n", " \"\"\"\n", " Initialize with state x0 and parameter r\n", " \"\"\"\n", " self.x, self.r = x0, r\n", "\n", " def update(self):\n", " \"Apply the map to update state.\"\n", " self.x = self.r * self.x *(1 - self.x)\n", "\n", " def generate_sequence(self, n):\n", " \"Generate and return a sequence of length n.\"\n", " path = []\n", " for i in range(n):\n", " path.append(self.x)\n", " self.update()\n", " return path" ] }, { "cell_type": "markdown", "id": "6b26f39b", "metadata": {}, "source": [ "Here’s an example of usage" ] }, { "cell_type": "code", "execution_count": null, "id": "68a3701a", "metadata": { "hide-output": false }, "outputs": [], "source": [ "ch = Chaos(0.1, 4.0) # x0 = 0.1 and r = 0.4\n", "ch.generate_sequence(5) # First 5 iterates" ] }, { "cell_type": "markdown", "id": "0aa9f513", "metadata": {}, "source": [ "This piece of code plots a longer trajectory" ] }, { "cell_type": "code", "execution_count": null, "id": "2cde069f", "metadata": { "hide-output": false }, "outputs": [], "source": [ "ch = Chaos(0.1, 4.0)\n", "ts_length = 250\n", "\n", "fig, ax = plt.subplots()\n", "ax.set_xlabel('$t$', fontsize=14)\n", "ax.set_ylabel('$x_t$', fontsize=14)\n", "x = ch.generate_sequence(ts_length)\n", "ax.plot(range(ts_length), x, 'bo-', alpha=0.5, lw=2, label='$x_t$')\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "e5206310", "metadata": {}, "source": [ "The next piece of code provides a bifurcation diagram" ] }, { "cell_type": "code", "execution_count": null, "id": "da58b0f9", "metadata": { "hide-output": false }, "outputs": [], "source": [ "fig, ax = plt.subplots()\n", "ch = Chaos(0.1, 4)\n", "r = 2.5\n", "while r < 4:\n", " ch.r = r\n", " t = ch.generate_sequence(1000)[950:]\n", " ax.plot([r] * len(t), t, 'b.', ms=0.6)\n", " r = r + 0.005\n", "\n", "ax.set_xlabel('$r$', fontsize=16)\n", "ax.set_ylabel('$x_t$', fontsize=16)\n", "plt.show()" ] }, { "cell_type": "markdown", "id": "ccd96198", "metadata": {}, "source": [ "On the horizontal axis is the parameter $ r $ in [(8.2)](#equation-quadmap2).\n", "\n", "The vertical axis is the state space $ [0, 1] $.\n", "\n", "For each $ r $ we compute a long time series and then plot the tail (the last 50 points).\n", "\n", "The tail of the sequence shows us where the trajectory concentrates after\n", "settling down to some kind of steady state, if a steady state exists.\n", "\n", "Whether it settles down, and the character of the steady state to which it does settle down, depend on the value of $ r $.\n", "\n", "For $ r $ between about 2.5 and 3, the time series settles into a single fixed point plotted on the vertical axis.\n", "\n", "For $ r $ between about 3 and 3.45, the time series settles down to oscillating between the two values plotted on the vertical\n", "axis.\n", "\n", "For $ r $ a little bit higher than 3.45, the time series settles down to oscillating among the four values plotted on the vertical axis.\n", "\n", "Notice that there is no value of $ r $ that leads to a steady state oscillating among three values." ] }, { "cell_type": "markdown", "id": "763e124e", "metadata": {}, "source": [ "## Special Methods\n", "\n", "\n", "\n", "Python provides special methods that come in handy.\n", "\n", "For example, recall that lists and tuples have a notion of length and that this length can be queried via the `len` function" ] }, { "cell_type": "code", "execution_count": null, "id": "fe7060d7", "metadata": { "hide-output": false }, "outputs": [], "source": [ "x = (10, 20)\n", "len(x)" ] }, { "cell_type": "markdown", "id": "061b9a75", "metadata": {}, "source": [ "If you want to provide a return value for the `len` function when applied to\n", "your user-defined object, use the `__len__` special method" ] }, { "cell_type": "code", "execution_count": null, "id": "5799e103", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class Foo:\n", "\n", " def __len__(self):\n", " return 42" ] }, { "cell_type": "markdown", "id": "4541a8f0", "metadata": {}, "source": [ "Now we get" ] }, { "cell_type": "code", "execution_count": null, "id": "e9eb3b95", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f = Foo()\n", "len(f)" ] }, { "cell_type": "markdown", "id": "ebe9f1a4", "metadata": {}, "source": [ "\n", "\n", "A special method we will use regularly is the `__call__` method.\n", "\n", "This method can be used to make your instances callable, just like functions" ] }, { "cell_type": "code", "execution_count": null, "id": "d0e00614", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class Foo:\n", "\n", " def __call__(self, x):\n", " return x + 42" ] }, { "cell_type": "markdown", "id": "c0ccac32", "metadata": {}, "source": [ "After running we get" ] }, { "cell_type": "code", "execution_count": null, "id": "caf2be3a", "metadata": { "hide-output": false }, "outputs": [], "source": [ "f = Foo()\n", "f(8) # Exactly equivalent to f.__call__(8)" ] }, { "cell_type": "markdown", "id": "8c377dc5", "metadata": {}, "source": [ "Exercise 1 provides a more useful example." ] }, { "cell_type": "markdown", "id": "a7a19269", "metadata": {}, "source": [ "## Exercises" ] }, { "cell_type": "markdown", "id": "45fd25de", "metadata": {}, "source": [ "## Exercise 8.1\n", "\n", "The [empirical cumulative distribution function (ecdf)](https://en.wikipedia.org/wiki/Empirical_distribution_function) corresponding to a sample $ \\{X_i\\}_{i=1}^n $ is defined as\n", "\n", "\n", "\n", "$$\n", "F_n(x) := \\frac{1}{n} \\sum_{i=1}^n \\mathbf{1}\\{X_i \\leq x\\}\n", " \\qquad (x \\in \\mathbb{R}) \\tag{8.3}\n", "$$\n", "\n", "Here $ \\mathbf{1}\\{X_i \\leq x\\} $ is an indicator function (one if $ X_i \\leq x $ and zero otherwise)\n", "and hence $ F_n(x) $ is the fraction of the sample that falls below $ x $.\n", "\n", "The Glivenko–Cantelli Theorem states that, provided that the sample is IID, the ecdf $ F_n $ converges to the true distribution function $ F $.\n", "\n", "Implement $ F_n $ as a class called `ECDF`, where\n", "\n", "- A given sample $ \\{X_i\\}_{i=1}^n $ are the instance data, stored as `self.observations`. \n", "- The class implements a `__call__` method that returns $ F_n(x) $ for any $ x $. \n", "\n", "\n", "Your code should work as follows (modulo randomness)" ] }, { "cell_type": "markdown", "id": "5507fb8f", "metadata": { "hide-output": false }, "source": [ "```python3\n", "from random import uniform\n", "\n", "samples = [uniform(0, 1) for i in range(10)]\n", "F = ECDF(samples)\n", "F(0.5) # Evaluate ecdf at x = 0.5\n", "```\n" ] }, { "cell_type": "markdown", "id": "19f0ec5e", "metadata": { "hide-output": false }, "source": [ "```python3\n", "F.observations = [uniform(0, 1) for i in range(1000)]\n", "F(0.5)\n", "```\n" ] }, { "cell_type": "markdown", "id": "5de5527a", "metadata": {}, "source": [ "Aim for clarity, not efficiency." ] }, { "cell_type": "markdown", "id": "abdb4789", "metadata": {}, "source": [ "## Solution to[ Exercise 8.1](https://python-programming.quantecon.org/#oop_ex1)" ] }, { "cell_type": "code", "execution_count": null, "id": "9d9cdbe5", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class ECDF:\n", "\n", " def __init__(self, observations):\n", " self.observations = observations\n", "\n", " def __call__(self, x):\n", " counter = 0.0\n", " for obs in self.observations:\n", " if obs <= x:\n", " counter += 1\n", " return counter / len(self.observations)" ] }, { "cell_type": "code", "execution_count": null, "id": "4a44a039", "metadata": { "hide-output": false }, "outputs": [], "source": [ "# == test == #\n", "\n", "from random import uniform\n", "\n", "samples = [uniform(0, 1) for i in range(10)]\n", "F = ECDF(samples)\n", "\n", "print(F(0.5)) # Evaluate ecdf at x = 0.5\n", "\n", "F.observations = [uniform(0, 1) for i in range(1000)]\n", "\n", "print(F(0.5))" ] }, { "cell_type": "markdown", "id": "44441e7f", "metadata": {}, "source": [ "## Exercise 8.2\n", "\n", "In an [earlier exercise](https://python-programming.quantecon.org/python_essentials.html#pyess_ex2), you wrote a function for evaluating polynomials.\n", "\n", "This exercise is an extension, where the task is to build a simple class called `Polynomial` for representing and manipulating polynomial functions such as\n", "\n", "\n", "\n", "$$\n", "p(x) = a_0 + a_1 x + a_2 x^2 + \\cdots a_N x^N = \\sum_{n=0}^N a_n x^n\n", " \\qquad (x \\in \\mathbb{R}) \\tag{8.4}\n", "$$\n", "\n", "The instance data for the class `Polynomial` will be the coefficients (in the case of [(8.4)](#equation-polynom), the numbers $ a_0, \\ldots, a_N $).\n", "\n", "Provide methods that\n", "\n", "1. Evaluate the polynomial [(8.4)](#equation-polynom), returning $ p(x) $ for any $ x $. \n", "1. Differentiate the polynomial, replacing the original coefficients with those of its derivative $ p' $. \n", "\n", "\n", "Avoid using any `import` statements." ] }, { "cell_type": "markdown", "id": "02986cf6", "metadata": {}, "source": [ "## Solution to[ Exercise 8.2](https://python-programming.quantecon.org/#oop_ex2)" ] }, { "cell_type": "code", "execution_count": null, "id": "89685b4c", "metadata": { "hide-output": false }, "outputs": [], "source": [ "class Polynomial:\n", "\n", " def __init__(self, coefficients):\n", " \"\"\"\n", " Creates an instance of the Polynomial class representing\n", "\n", " p(x) = a_0 x^0 + ... + a_N x^N,\n", "\n", " where a_i = coefficients[i].\n", " \"\"\"\n", " self.coefficients = coefficients\n", "\n", " def __call__(self, x):\n", " \"Evaluate the polynomial at x.\"\n", " y = 0\n", " for i, a in enumerate(self.coefficients):\n", " y += a * x**i\n", " return y\n", "\n", " def differentiate(self):\n", " \"Reset self.coefficients to those of p' instead of p.\"\n", " new_coefficients = []\n", " for i, a in enumerate(self.coefficients):\n", " new_coefficients.append(i * a)\n", " # Remove the first element, which is zero\n", " del new_coefficients[0]\n", " # And reset coefficients data to new values\n", " self.coefficients = new_coefficients\n", " return new_coefficients" ] } ], "metadata": { "date": 1710455932.8356006, "filename": "python_oop.md", "kernelspec": { "display_name": "Python", "language": "python3", "name": "python3" }, "title": "OOP II: Building Classes" }, "nbformat": 4, "nbformat_minor": 5 }