[Tutor] Object references in Python
Steven D'Aprano
steve at pearwood.info
Tue Jul 16 16:33:13 EDT 2019
On Tue, Jul 16, 2019 at 12:08:10PM +0000, AHIA Samuel wrote:
> Please what are references in Python development?
x = 19
y = x
The name "x" is a reference to the int 19; the name y is a reference to
the same int.
x = "Hello world"
Now the name "x" is a reference to the string "Hello world". y remains a
reference to the int 19.
x = None
Now the name "x" is a reference to the None object.
x = [100, 200, 300]
Now the name "x" is a reference to a list with three items:
- The first item of x, x[0], is a reference to the int 100.
- The second item of x, x[1], is a reference to the int 200.
- The third item of x, x[2], is a reference to the int 300.
y = x
Now y is no longer a reference to the int 19 as before, but is a
reference to the same list that x is a reference to. There are now two
references to the list object: x and y.
(If you are a C programmer, you can think of x and y both being pointers
to the same list. This is not completely correct, but it isn't far
wrong.)
Since x and y are references to the same list, we can equally say:
- The first item of y, y[0], is a reference to the int 100.
- The second item of y, y[1], is a reference to the int 200.
- The third item of y, y[2], is a reference to the int 300.
x.append(None)
Now the name x is still a reference to the same list as before, except
that we have added a new item to the end of the list:
- The fourth item of x, x[3], is a reference to the None object.
- The fourth item of y, y[3], is a reference to the None object.
Since both x and y are references to the same list, any change to the x
list is a change to the y list (since they are the same).
class Parrot:
def __init__(self, colour="blue"):
self.colour = colour
def speak(self):
print("Polly wants a cracker!")
Now the name "Parrot" is a reference to the class "Parrot".
x = Parrot()
Now x is a reference to a Parrot instance. y remains a reference to the
list.
x.colour is a reference to the string "blue" (by default).
x.speak is a reference to the "speak" method of Parrot objects.
Does this help?
--
Steven
More information about the Tutor
mailing list