I've managed to create a scenario in which editing an object in a list of
objects seems to edit every object in the list, rather than just the one.
I'm totally stumped and wondered if anyone would be kind enough to read my
explanation and see if they have any suggestions. I have probably stumbled
into some typical newbie problem, but anyway:
I have two classes, Area and Agent:
class Agent:
def __init__(self,name):
self.name = name
class Area:
def __init__(self, occupants = []):
self.occupants = occupants
Now, I want to create a 'virtual environment' as a 2D list of Area
objects, so:
environment = []
for x in range(0,10):
environment.append([])
for y in range(0,10):
new_area = Area()
environment[-1].append(new_area)
This works fine, environment is now a 10*10 2D list of Area objects, and
the occupants member of each Area object is [].
Now, I want to add an occupants, in the form of an Agent object, to an
area in the environment:
new_agent = Agent("Bob")
environment[4][5].occupants.append(new_agent)
This is where it goes wrong, it looks as if new_agent gets appended to the
occupants list of EVERY Area object in environment. For example, the
following code:
for areas_list in environment:
for area in areas_list:
print len(area.occupants)
Will print out `1` 100 times over.
I must be making some really stupid mistake, but this just doesn't look
like the list behaviour I would expect. What's going on here?
-- 4 1155
Sean Hammond schrieb: I've managed to create a scenario in which editing an object in a list of objects seems to edit every object in the list, rather than just the one. I'm totally stumped and wondered if anyone would be kind enough to read my explanation and see if they have any suggestions. I have probably stumbled into some typical newbie problem, but anyway:
just a hint def foo(val,lst=[]):
.... lst.append(val)
.... print lst
....
foo(1)
[1] foo(2)
[1, 2] foo(3)
[1, 2, 3] foo(4,[0])
[0, 4]
here list lst is created and bound once
compare with this one (which is what you really want)
def bar(val, lst=None):
.... if lst is None:
.... lst = []
.... lst.append(val)
.... print lst
.... bar(1)
[1] bar(2)
[2] bar(3, [0])
[0, 3]
hth, Daniel
Sean Hammond wrote: class Area: def __init__(self, occupants = []): self.occupants = occupants
.... I must be making some really stupid mistake, but this just doesn't look like the list behaviour I would expect. What's going on here?
Whenever you use the default value for occupants in the constructor you
reuse the same list. Don't use mutable objects as default values:
def __init__(self, occupants=None):
if occupants is None:
self.occupants = []
else:
self.occupants = occupants
Sean Hammond wrote: I've managed to create a scenario in which editing an object in a list of objects seems to edit every object in the list, rather than just the one. I'm totally stumped and wondered if anyone would be kind enough to read my explanation and see if they have any suggestions. I have probably stumbled into some typical newbie problem, but anyway:
some useful resources: http://docs.python.org/tut/node6.htm...00000000000000
(see the paragraph that starts with "important warning") http://www.python.org/doc/faq/genera...etween-objects http://docs.python.org/ref/function.html
(see the paragraph that starts with "Default parameters are evaluated when the
function definition is executed")
(you cannot say we didn't warn you ;-)
</F>
Right, thanks everyone, that's a useful lesson learned. As I suspected I
was being tripped over by some feature of Python I was unaware of. I had
been looking up lists in the documentation, not functions, and could find
no explanation.
Prbolem solved!
-- This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Ben |
last post by:
Hi all,
I'm trying to figure out how how complex map, filter and reduce work
based on the following piece of code from
http://www-106.ibm.com/developerworks/linux/library/l-prog.html :
...
|
by: Markus Franz |
last post by:
Hi.
Today I created a script called load.py for using at the command line
written in Python 2.3.
This script should load as many websites as given on the comand line and
print them with a...
|
by: Wolfgang.Stoecher |
last post by:
Hello,
I'm new to Python and playing around. I'm confused by the following
behaviour:
>>> l1 = # define list
>>> l2 = l1 # copy of l1 ?
>>> l2,l1
(, )
>>> l2.extend(l1) # only l2 should...
|
by: brian.bird |
last post by:
Can anyone explain the behaviour of python when running this script?
>>> def method(n, bits=):
.... bits.append(n)
.... print bits
....
>>> method(1)
>>> method(2)
|
by: na1paj |
last post by:
here's a simple linked list program. the DeleteNode function is
producing an infinit loop i think, but i can't figure out where..
#include <stdio.h>
typedef struct
{
char *str; //str is a...
|
by: conor.robinson |
last post by:
The Problem (very basic, but strange):
I have a list holding a population of objects, each object has 5 vars
and appropriate funtions to get or modify the vars. When objects in
the list have...
|
by: abcd |
last post by:
class Foo:
def __init__(self, name, data=):
self.name = name
self.data = data
def addData(self, val):
self.data.append(val)
f = Foo('a')
|
by: matthewperpick |
last post by:
Check out this toy example that demonstrates some "strange" behaviour
with keyword arguments and inheritance.
=================================
class Parent:
def __init__(self, ary = ):...
|
by: Dox33 |
last post by:
I ran into a very strange behaviour of raw_input().
I hope somebody can tell me how to fix this.
(Or is this a problem in the python source?)
I will explain the problem by using 3 examples....
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: aa123db |
last post by:
Variable and constants
Use var or let for variables and const fror constants.
Var foo ='bar';
Let foo ='bar';const baz ='bar';
Functions
function $name$ ($parameters$) {
}
...
|
by: ryjfgjl |
last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: nemocccc |
last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
|
by: Hystou |
last post by:
There are some requirements for setting up RAID:
1. The motherboard and BIOS support RAID configuration.
2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
| |