I am writing a simple dynamics model that includes position, velocity, ect for multiple objects.
class airplane
history=[]
def record(self,time,timestep=.1):
self.history.append([time*timestep,self.position[0],self.position[1],self.position[2]])
def output(self):
self.data=pandas.DataFrame(self.history,columns=['time','x','y','z'])
for i in range(10):
airplane1.record(i)
airplane2.record(i)
airplane1.output()
airplane2.output()
Each data frame has 20 rows containing the alternating positions of each airplane. How do I make record only append data to the history list of the called object?
You need to make history
an instance attribute, rather than a class attribute that is shared by all instances of the class, by creating it in an __init__
method. I have corrected your code: You need to create instances airplane1
and airplane2
before you can use them and nowhere do you create instance attribute list position
, so I have commented out the reference to that and substituted constants for now (you need to correct this). I also added a print
statement to demonstrate the output. Also, it is usual to name classes with capital letters.
import pandas
class airplane:
def __init__(self):
self.history = []
def record(self,time,timestep=.1):
#self.history.append([time*timestep,self.position[0],self.position[1],self.position[2]])
self.history.append([time*timestep, 0, 1, 2])
def output(self):
self.data=pandas.DataFrame(self.history,columns=['time','x','y','z'])
print(self.data)
airplane1 = airplane()
airplane2 = airplane()
for i in range(10):
airplane1.record(i)
airplane2.record(i)
airplane1.output()
airplane2.output()
Prints:
time x y z
0 0.0 0 1 2
1 0.1 0 1 2
2 0.2 0 1 2
3 0.3 0 1 2
4 0.4 0 1 2
5 0.5 0 1 2
6 0.6 0 1 2
7 0.7 0 1 2
8 0.8 0 1 2
9 0.9 0 1 2
time x y z
0 0.0 0 1 2
1 0.1 0 1 2
2 0.2 0 1 2
3 0.3 0 1 2
4 0.4 0 1 2
5 0.5 0 1 2
6 0.6 0 1 2
7 0.7 0 1 2
8 0.8 0 1 2
9 0.9 0 1 2
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments