Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Simulated Pointers With Mutable Types

In this lesson, you’ll simulate pointer behavior in Python using a mutable object type. This is not actual pointer behavior. These operations are more memory expensive than they would be in C.

carl on July 15, 2020

I think that it would have been very instructive, as your second example, to point out that objects of classes that you create can also be mutable. A simple type like this mutable Cartesian Point class illustrates the same concept I think you were making with your second example, but is less complicated

class Point(object):

    def __init__(self, x, y):
        self._x = x
        self._y = y

    def set_x(self, x):
        self._x = x

    def set_y(self, y):
        self._y = y

    def __repr__(self):
        return f"({self._x},{self._y})"


p = Point(0, 0)
print(id(p), p)
p.set_x(1)
print(id(p), p)
p.set_y(1)
print(id(p), p)

If we run this we see that the name p refers to the same object the entire time, but because we exposed those set methods, we can mutate its state. The names self._x or self._y will point to different (immutable) values after one of the set methods is used, effectively changing the mutable state of p.

carl on July 15, 2020

Taking that one step further, if we now define a function to reset both coordinates of a Point, we’ll see that it’s still mutating p. This is pass-by-assignment in action.

def reset(q):
    q.set_x(0)
    q.set_y(0)


p = Point(1, 1)
print(id(p), p)
reset(p)
print(id(p), p)

Become a Member to join the conversation.