Creating object in function doesn't seem to create a new object.
Paul Childs
pchilds at gmail.com
Tue Jun 3 15:18:18 EDT 2008
Hi folks,
I'll start off with the code I wrote...
(ActivePython 2.4 on Windows XP SP2)
-------------------------------
class FlightCondition(object):
lsf = [0,'Low Speed Flare']
vto = [0,'Vertical Take-Off']
def get_flight_condition(flight_data):
fc1 = FlightCondition()
for row in flight_data:
fc1.lsf[0] += 1
fc1.vto[0] += 1
print 'in function get_flight_condition'
print fc1.lsf
print fc1.vto
return fc1
for count in range(3):
fc = get_flight_condition([1,2,3])
print 'returned fc'
print fc.lsf
print fc.vto
---------------------------------
When I run it I get...
in function get_flight_condition
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
returned fc
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
in function get_flight_condition
[6, 'Low Speed Flare']
[6, 'Vertical Take-Off']
returned fc
[6, 'Low Speed Flare']
[6, 'Vertical Take-Off']
in function get_flight_condition
[9, 'Low Speed Flare']
[9, 'Vertical Take-Off']
returned fc
[9, 'Low Speed Flare']
[9, 'Vertical Take-Off']
---------------------------------
I thought that when I wrote fc1 = FlightCondition() in the function it
would create a new FlightCondition object which would be passed back
every time.
Instead it seems to re-reference the old version and continue to add
to it.
---------------------------------
What I expected was...
in function get_flight_condition
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
returned fc
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
in function get_flight_condition
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
returned fc
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
in function get_flight_condition
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
returned fc
[3, 'Low Speed Flare']
[3, 'Vertical Take-Off']
---------------------------------
Could someone please explain to me why I get the output I did instead
of what I expected.
How do I code my function so I get a new fc1 every time and my desired
output?
Thanks in advance.
/Paul
More information about the Python-list
mailing list