Attributes in Mutable Objects
00:00 Another way Python programmers implement pass by reference is by using object attributes. But first, a definition. A Python object is considered mutable if it can be changed in place without being reassigned.
There aren’t many of these in Python. Objects of the collection types
set, and dictionaries are mutable. And objects of programmer-created classes are mutable as well. If you’re not mutable, then you’re immutable.
00:46 But here, we’re focusing on mutable objects. Since an object variable and the parameter it’s passed to are bound to the same object, a change made inside the function to that object through its parameter reference will be reflected by the argument variable after the function ends.
01:07 So basically, you can perform pass by reference if your arguments are mutable objects. In this lesson, you’ll see an example where you create your own custom objects, and in the next lesson, you’ll look at modifying collection objects using pass by reference.
Here’s a new version of the
square() function, one that expects the object passed to have an attribute
.n, and it will square that attribute’s value and save it back to that attribute, just like the C++ function did with the parameter
To use it, create an object with an attribute
.n, where that attribute holds the value you want to pass by reference. So again, this version of the
square() function takes an argument which will be bound to the parameter name
instance, named like this since it’s an instance of some class.
Well, for a class that doesn’t really need any methods and is only going to have attributes you create as needed, you can use Python’s
SimpleNamespace type. It’s basically an empty class definition.
SimpleNamespace is exactly what we want: a class to create objects, give an attribute, and use it. So, we will create an object of the
SimpleNamespace class, give it an attribute
.n and assign it a value of
4, then call this version of the
square() function, passing that object as the argument. When I run this script, after performing
square(), you will see that the attribute
.n will have indeed be changed to
there’s the object showing the class attribute
.n. But then if I call the function that modifies that attribute, the value of that attribute for this object is
16 but the class attribute is still
Become a Member to join the conversation.