NB: Putting Your Class in a File

Programming for Data Science

In this notebook, we demonstrate that you can put our class code in a separate .py file and then call it from within a notebook.

This is normal practice — class files cannot reside in notebooks if they are to be used by other code!

Open the file diegame.py in the course repo to inspect the code.

!more diegame.py
import pandas as pd

class DieGame():
    """
    Just another Python class.
    """
    n_rolls = 10
    weights = [1,1,1,1,1,1]
    
    def __init__(self):
        pass
        
    def create_die(self):
        self.n_sides = len(self.weights)
        self.my_probs = [i/sum(self.weights) for i in self.weights]
        self.die = pd.DataFrame({
            'side': range(1, self.n_sides + 1),
            'weights': self.my_probs
        })
    
    def roll_die(self):
        results = []
        for i in range(self.n_rolls):
m--More--(38%)

We import the class in diegame.py into this notebook.

from diegame import DieGame

We initialize two objects.

dg1 = DieGame()
dg2 = DieGame()
dg1.do_it_all()
Sides: 6
Model:
1    0.17
2    0.17
3    0.17
4    0.17
5    0.17
6    0.17
dtype: float64
Rolls: 10

dg2.do_it_all()
Sides: 6
Model:
1    0.17
2    0.17
3    0.17
4    0.17
5    0.17
6    0.17
dtype: float64
Rolls: 10

To demonstrate the point made in the previous notebook about class and instance attributes, let’s update our objects.

dg1.n_rolls = 20 # This overrides the Class attribute
dg1.weights = [1, 10, 1, 1, 1, 1] # So does this
dg2.weights.append(1) # But this also alters the static because this is not an assignment!
DieGame.n_rolls = 50 # This should change dg2 but not dg1
results = [
    ('n_roles', dg1.n_rolls, dg2.n_rolls, DieGame.n_rolls),
    ('weights', dg1.weights, dg2.weights, DieGame.weights)
]
import pandas as pd
pd.DataFrame(results, columns=['attribute', 'dg1', 'dg2', 'DieGame']).set_index('attribute').T
attribute n_roles weights
dg1 20 [1, 10, 1, 1, 1, 1]
dg2 50 [1, 1, 1, 1, 1, 1, 1, 1]
DieGame 50 [1, 1, 1, 1, 1, 1, 1, 1]