Attributes on self contains the "internal" state of the object. But Python lets anyone access that internal state directly via attributes on the object itself.
The constructor is a special method that exists to create the "initial state" of the object and set attributes on self.
The constructor is called when the class is instantiated.
Using classes
classDataStore():def__init__(self, location):
self.data = location
defget_data(self):# read from self.location# get latest data as "data"return data
# __init__ called:
data_store = DataStore('path/to/data')
data_store.get_data()
Let's create a real DataStore class. Each instance of DataStore is used to access data from a different "location".
Other parts of the program can now use the data_store instance without having to know anything about how it gets the data or where.
This means the storage of the data is decoupled from the rest of the program.
Loose Coupling
If with think of our system as a set of component parts, we can begin to think of what would happen if we needed to change one of the parts.
We say that two parts are tightly coupled if, when we change something in one part, we need make (big) changes in the other.
We say that two parts are loosely coupled if we can change the inner workings of one part without needed to change anything about the other.
Loose Coupling
defclean_data(data_store):
data = data_store.get_data()
# clean datareturn data
deftrain_model(data, model):# do some trainingreturn model
data_store = DataStore('/path/to/data')
data = clean_data(data_store)
train_model(data, model)
We can imagine our data_store instance being used like this.
How does use of the DataStore class enable loose coupling?