Below a runnable codesnippet with behavior I cannot explain:
name_generator
should create a new LetterMan
object in each iteration, appends an arbitrary letter and yield it.
What happens is that on each iteration, a letter is somehow appended to the supposedly new object. The result of the script is:
class LetterMan(object):
def __init__(self, name, letterlist=[]):
self.letterlist = letterlist
self.name = name
def add_letter(self, letter):
self.letterlist.append(letter)
def name_generator():
for name in ["Andrew", "Bryan", "Casey"]:
l = LetterMan(name)
l.add_letter(name[-1])
yield l
if __name__ == '__main__':
n = name_generator()
for lman in n:
print lman.name, lman.letterlist
# Andrew ['w']
# Bryan ['w', 'n']
# Casey ['w', 'n', 'y']
I am expecting:
# Andrew ['w']
# Bryan ['n']
# Casey ['y']
Is it some sort of optimization? Why is there no new object created on each iteration? How would I achieve the expected result?
I already tried deleting the object after each yield
with no result
I am using python 2.7.3
on ubuntu