Abstract data types
Let's now leave behind efficiency and metrics for the moment, and touch on another building block that will resurface repeatedly in this course: abstract data types, or ADTs.
What are ADTs?
To summarize, ADTs define the semantics of how a data structure should behave, including the operations that the data structure should support. However, an ADT doesn't define how the data structure should be implemented -- it is only an abstract description.
ADTs and Python
Now that we know what an ADT is in general terms, let's think about how to use ADTs in code.
Python does not have a specific language feature that represents an ADT. When we need to implement an ADT using a Python class, we will include the name of the ADT in the class name. This way, we will have a hint about the expected behavior of objects of that class.
For example, if we wanted to create a list-based implementation of a tuple as described in the video, it might look like this:
class ListTuple:
def __init__(self, a, b):
self.items = [a, b]
def get_item_a(self):
return self.items[0]
def get_item_b(self):
return self.items[1]
def set_item_a(self, new_a):
self.items[0] = new_a
def get_item_b(self, new_b):
self.items[1] = new_b
Under the hood, the tuple abstraction is implemented as a Python list. On the other hand, if we wanted to create a variable-based representation of a tuple, it would look like this:
class TwoVariableTuple:
def __init__(self, a, b):
self.a = a
self.b = b
def get_item_a(self):
return self.a
def get_item_b(self):
return self.b
def set_item_a(self, new_a):
self.a = new_a
def get_item_b(self, new_b):
self.b = new_b
Both ListTuple
and TwoVariableTuple
provide the operations of a tuple, just implemented in different ways!
You might be wondering at this point why we would need to have multiple implementations of an ADT if they provide the same behavior. The answer is efficiency. One implementation of an ADT might be more efficient than another implementation of an ADT. Once we see more fundamental ways of organizing data other than lists, the differences in efficiency in how we implement ADTs will become clearer.