Cheat Sheets

Classes and Objects

Lesson

You can implement data structures using "Objects".

Objects are just HashMaps (dictionaries) but with nicer syntax.

Using HashMaps

For interviews we usually prefer implementing data structures with HashMaps instead of Objects. For example, here's how we'd make a LinkedList:

node1 = { 'val': 1 }
node2 = { 'val': 2 }
node3 = { 'val': 3 }
node1['next'] = node2
node2['next'] = node3

node1['val']                 # 1
node1['next']['val']         # 2
node1['next']['next']['val'] # 3

Using Objects

But instead of using HashMaps, you might want (or be told) to implement a data structure using objects. Here's how you might implement the above code using objects. We'll assume we already wrote the class ListNode.

node1 = ListNode(1)
node2 = ListNode(2)
node3 = ListNode(3)
node1.next = node2
node2.next = node3

node1.val           # 1
node1.next.val      # 2
node1.next.next.val # 3

Objects like node1, node2, and node3 behave exactly the same as HashMaps. They just have different syntax and let you write less code sometimes. Anything you do with an object, you could have done with a HashMap and functions instead. It's just a matter of preference which to use.

Now that you know about objects, we'll walk you through classes, which create objects.

Writing Classes

There are only 2 things about classes you need to know.

1. You can write a function that runs when you create a new object, like when you call x = ListNode(). The function is always called __init__.

2. When you define a new function in a Class, you need to give the function an extra input. People usually call it the self input. This input gives you access to the object you're dealing with. It's automatically passed in, and you don't have to specify it when you actually call the function.

Here's an example of a Class:

class ListNode:

    # runs when object is created
    def __init__(self, v):
        self.val = v

    # object can call this function
    def addOne(self):
        self.val = self.val + 1

And here's an example of how you use this Class:

node = ListNode(10) # calls __init__(node, 10)
print(node.val) # 10
node.addOne() # calls addOne(node)
print(node.val) # 11
Mark as Completed:
Submits:
test
Test your code to get an output here!