OOP is one of several approaches to program design and execution supported by Python.
Central to OOP are objects, all of which have particular:
Everything in Python is an object - strings, lists, dictionaries, functions, etc...
All objects are instances of a class, having been created (or instantiated) from a particular class definition.
Let's take a look at an example:
class User:
def __init__(self, name, age):
self.name = name
self.age = age
def adult(self):
return True if self.age >= 18 else False
We can see in our User definition (classes are capitalized by convention), what look much like functions.
These are methods, which are simply functions which are associated with (and called from) a particular object.
self¶self is used by convention to represent the object itself in the method definitions (this could be any string as long as the same string was used consistently throughout the class definition).
__init__¶This is a special method, which is called automatically when a new object of the given class is instantiated.
user_01 = User('Dave', 17)
user_01.age
17
User object, we can access its attributes using dot notationuser_01.adult()
False
adult() method on the user_01 objectuser_01.age += 1
user_01.adult()
True
age attribute for user_01, and the .adult() method accordingly returns a different result As before, we'll just focus on what's new here:
from spotter import Spotter
...
s = Spotter(client_id, client_secret)
...
track_info = s.get_item('tracks', track_id)
Spotter class from spotter.py s, using our client_id and client_secret.get_item() method of s, providing 'tracks' and a track_id as argumentsSpotter() class¶Take a look at spotter.py, starting with the __init__ method.
get_token() method, which will make a call to the API to fetch an access_token and update the token attribute of the given object with the result.get_item() method¶category and item_idtracks or albumsIn main.py, this method can be called on the s object, and the API call is made using its own headers attribute - which contains the token attribute that was assigned when s was instantiated.
We can continue to use s.get_item() in the console (i.e. without having to re-create s), until the token expires.
Next, we'll see how we can avoid having to create a new Spotter object when the token has expired...