[Tutor] Baffling problem with a list of objects sharing a property
Alex Hall
ahall at autodist.com
Wed May 25 12:05:16 EDT 2016
Hello all,
I've used Python off and on for years, and consider myself pretty good with
it. I was on this list quite a while ago and learned a lot, but hadn't used
Python for a while so eventually unsubscribed.
Now I'm using Python for work, and have run into a problem that has me
baffled. It's as though a bunch of class instances in a list are sharing a
single property. Have a look at this script:
class Test(object):
def __init__(self, name, paths=[]):
self.name = name
self.paths = paths
def __str__(self):
return "Name: {name}. Path count: {paths}.".format(name=self.name,
paths=len(self.paths))
#end class Test
tests = [
Test("a"),
Test("b"),
Test("c"),
]
for t in tests:
print t
t.paths.append("a")
print t
If you run that, something odd happens. Instead of each Test instance
getting one item appended to its "paths" property, Test C ends up with
three, B with 2, and A with 1. It's as though appending to t.paths appends
to the paths property for all the instances in the list, not just the
current one. I've been working on this for over an hour and just can't
figure out what the deal is. I'm emailing spreadsheets using Python, and
this problem is causing all the spreadsheets to be emailed to everyone,
when it should be just one spreadsheet per person. Oh, the same problem
happens if you remove (object) from the class definition, and if your loop
is instead:
for i in range(len(tests)):
print tests[i]
tests[i].paths.append("a")
print tests[i]
If anyone can explain what's happening, I'd very much appreciate it. I'm on
Windows 7, Python 2.7.11. Thanks.
--
Alex Hall
Automatic Distributors, IT department
ahall at autodist.com
More information about the Tutor
mailing list