Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

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.

Avatar image for carl

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.

Avatar image for carl

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.