I have a Ring structure implemented as follows (based on a cookbook recipe I found):
class Ring(list):
def turn(self):
last = self.pop(0)
self.append(last)
def setTop(self, objectReference):
if objectReference not in self:
raise ValueError, "object is not in ring"
while self[0] is not objectReference:
self.turn()
Say I do the following:
x = Ring([1,2,3,4,4])
x.setTop(4)
My code will always set the first 4 (currently x[3]) to x[0]. It seems (via object identity and hash id testing between x[3] and x[4]) that Python is reusing the 4 object.
How do I tell Python that I really want the second 4 (currently x[4]) to be at the top?
Apologies for the basic question ... one of the downfalls of being a self-taught beginner.
Thanks,
Mike
===EDIT===
For what it's worth, I dropped the setTop method from the class. I had added it to the standard recipe thinking "hey, this would be neat and might be useful." As the answers (esp. "what's the difference", which is spot on) and my own experience using the structure show, it's a crappy method that doesn't support any of my use cases.
In other words, adding something because I could instead of fulfilling a need = fail.
From Learning Python, 4th edition -- Chapter 6:
At least conceptually, each time you generate a new value in your script by running an expression, Python creates a new object (i.e., a chunk of memory) to represent that value. Internally, as an optimization, Python caches and reuses certain kinds of un- changeable objects, such as small integers and strings (each 0 is not really a new piece of memory—more on this caching behavior later). But, from a logical perspective, it works as though each expression’s result value is a distinct object and each object is a distinct piece of memory.
The question is..
if x[3] is x[4]:
print "What's the difference?"
If you know you want the second, then do
x = Ring([1,2,3,4,4])
x.setTop(4)
x.turn()
x.setTop(4)
You can enhance setTop() to take an additional parameter and do it inside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With