Trouble with +=

self.value = 5
current = self.value
self.value += 1
return current

Would current be 5 since += is after the variable (current = self.value)? If not, how so?


This sounds like you are wondering the difference between passing by value and passing by reference? Anyways, you are absolutely correct that current would equal 5 because it was given the value of self.value before the next line self.value += 1 that changes the 5 to a 6!

1 Like

I saw in a youtube tutorial that the reference was added with an addition 1 and then returned that way using this exact same setup. After the guy in the video ran his code, it worked. That confused me big time, so what do you think?

That’s interesting. Do you happen to have the entire code script so we can look for clues? Or the video?

At the moment that’s only defining constructors and a variable (unless I’m missing something).

Do you happen to have a link to the video? (i’m curious too now!)

This is a custom iterator. Add the following code after the nums instance:

for i in range(11):

Traceback (most recent call last):
File “”, line 18, in
File “”, line 11, in next
raise StopIteration

This might be beyond the scope of the Codecademy intent. Maybe a moderator will chime in.

1 Like

@harrjt has the right interpretation of the code you provided in that image. As for the first question,
yes, current would still be 5. Integer objcects are not mutable, using the same name for a different integer would change the reference and not the object. You could test this relatively quickly.

a = 2
b = a
print(id(b)) # Same id
a = 4
print(id(a)) # Not the same object in memory.
a is b # Evaluates to False

I’d be wary of stating that values change, all you’re doing with those statements is add/removing references to particular objects.

As an additional piece of half-remembered info…
It’s worth keeping in mind there’s something about a number of python integers, -5 to 256 I believe that are held as objects in memory from start-up. You’d have to look that up though as I can’t remember it well enough to try and explain it. Sorry.