<jupyter_start><jupyter_text>Classes Notebook created: 2018-03-20 23:51:38  Generated from: _build_py/py/python_oop.rst   We've seen that in Python there are lots of native types that we can build and useThey hold data and have methods that act on that data:<jupyter_code>x = [1, 5, 4]
x.sort()
x<jupyter_output><empty_output><jupyter_text>Now we want to build our ownLet's say we want a consumer type that can earn and spend money  Example 1<jupyter_code>class Consumer:

    def __init__(self, w):
        "Initialize consumer with w dollars of wealth"
        self.wealth = w

    def earn(self, y):
        "The consumer earns y dollars"
        self.wealth += y

    def spend(self, x):
        "The consumer spends x dollars if feasible"
        new_wealth = self.wealth - x
        if new_wealth < 0:
            print("Insufficent funds")
        else:
            self.wealth = new_wealth<jupyter_output><empty_output><jupyter_text>Now let's instantiate a consumer:<jupyter_code>cns = Consumer(10)  
cns.wealth
cns.spend(4)
cns.wealth
cns.earn(15)
cns.wealth
cns.spend(100)<jupyter_output>Insufficent funds<jupyter_text>We can make multiple instances with their own *instance data*<jupyter_code>c1 = Consumer(10)
c2 = Consumer(12)
c2.spend(4)
c2.wealth
c1.wealth<jupyter_output><empty_output><jupyter_text>Instance data is stored as a dict<jupyter_code>c1.__dict__
c2.__dict__<jupyter_output><empty_output><jupyter_text>Example 2<jupyter_code>import numpy as np

class Solow:
    r"""
    Implements the Solow growth model with update rule

        k_{t+1} = [(s z k^α_t) + (1 - δ)k_t] /(1 + n)
    
    """
    def __init__(self, n=0.05,  # population growth rate
                       s=0.25,  # savings rate
                       δ=0.1,   # depreciation rate
                       α=0.3,   # share of labor
                       z=2.0,   # productivity
                       k=1.0):  # current capital stock

        self.n, self.s, self.δ, self.α, self.z = n, s, δ, α, z
        self.k = k

    def update(self):
        "Update the current state (i.e., the capital stock)."
        # Unpack parameters (get rid of self to simplify notation)
        n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z
        # Apply the update rule
        self.k = (s * z * self.k**α + (1 - δ) * self.k) / (1 + n)

    def steady_state(self):
        "Compute the steady state value of capital."
        # Unpack parameters (get rid of self to simplify notation)
        n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z
        # Compute and return steady state
        return ((s * z) / (n + δ))**(1 / (1 - α))
     
    def generate_sequence(self, t):
        "Generate and return a time series of length t"
        path = []
        for i in range(t):
            path.append(self.k)
            self.update()
        return path
import matplotlib.pyplot as plt

s1 = Solow()  
s2 = Solow(k=8.0)

T = 60
fig, ax = plt.subplots(figsize=(9, 6))

# Plot the common steady state value of capital
ax.plot([s1.steady_state()]*T, 'k-', label='steady state')

# Plot time series for each economy
for s in s1, s2:
    lb = f'capital series from initial state {s.k}'
    ax.plot(s.generate_sequence(T), 'o-', lw=2, alpha=0.6, label=lb)

ax.legend()
plt.show()<jupyter_output><empty_output><jupyter_text>ExerciseAdd a method to the class called `plot_time_series` that takes as its arguments* an `ax` object (of type `matplotlib.axes._subplots.AxesSubplot`)* an initial condition* a `series_length` parameterand adds to the `ax` object a time series plot of length `series_length`<jupyter_code>for i in range(40):
    print("solution below")
import numpy as np

class Solow:
    r"""
    Implements the Solow growth model with update rule

        k_{t+1} = [(s z k^α_t) + (1 - δ)k_t] /(1 + n)
    
    """
    def __init__(self, n=0.05,  # population growth rate
                       s=0.25,  # savings rate
                       δ=0.1,   # depreciation rate
                       α=0.3,   # share of labor
                       z=2.0,   # productivity
                       k=1.0):  # current capital stock

        self.n, self.s, self.δ, self.α, self.z = n, s, δ, α, z
        self.k = k

    def h(self):
        "Evaluate the h function"
        # Unpack parameters (get rid of self to simplify notation)
        n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z
        # Apply the update rule
        return (s * z * self.k**α + (1 - δ) * self.k) / (1 + n)

    def update(self):
        "Update the current state (i.e., the capital stock)."
        self.k =  self.h()
        
    def steady_state(self):
        "Compute the steady state value of capital."
        # Unpack parameters (get rid of self to simplify notation)
        n, s, δ, α, z = self.n, self.s, self.δ, self.α, self.z
        # Compute and return steady state
        return ((s * z) / (n + δ))**(1 / (1 - α))
     
    def generate_sequence(self, t):
        "Generate and return a time series of length t"
        path = []
        for i in range(t):
            path.append(self.k)
            self.update()
        return path
    
    def plot_time_series(self, ax, k0=4.0, series_length=50):
        self.k = k0
        path = self.generate_sequence(series_length)
        ax.plot(path, '-o')
sol = Solow()

fig, ax = plt.subplots()
sol.plot_time_series(ax)

plt.show()<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1174074074074074, 'fraction_numerical': 0.01925925925925926, 'mean_word_length': 2.295302013422819, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '7', 'dir': 'jupyter-structured-clean-dedup', 'id': '659591', 'license': 'BSD-3-Clause', 'n_tokens_mistral': 1935, 'n_tokens_neox': 1827, 'n_words': 576, 'path': 'day1/python_oop.ipynb', 'repo_name': 'fkazemian/columbia_mini_course', 'size': '5400'}