Reputation: 31
I am trying to follow instructions from Effective Computation in Physics, a Field Guide to Research with Python book (by Anthony Scopatz and Kathryn Duff. In the OOP chapter(specifically page 136 in my version), I tried copying the code and ran the code below:
# import the Particle class from the particle module
from particle import Particle as p
# create an empty list to hold observed particle data
obs = []
# append the first particle
obs.append(p.Particle())
# assign its position
obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}
# append the second particle
obs.append(p.Particle())
# assign the position of the second particle
obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}
# print the positions of each particle
print(obs[0].r)
print(obs[1].r)
The result is supposed to give the position typed in. However, the code did not work like this. Instead, I played around with the code and this code worked instead:
# Import the Particle class from the particle Module
from particle import Particle as p
# Create an empty list
obs = []
# Append first element
obs.append(p)
# Assign its position
obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}
# Append second particle
obs.append(particle())
# Assign second position
obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}
print(obs[0].r)
print(obs[1].r)
I would love to understand why and what is going on. I am currently reviewing how OOP works and am using Python for now. Please respond! I want to learn how and why does this work!
Upvotes: 2
Views: 57
Reputation: 309
I'm not sure I understood everything but if you want to turn your code in POO you can try something like this:
from particle import Particle as p
class Myclass:
def __init__(self):
# Create an empty list
self.obs = []
# Append first element
self.obs.append(p)
# Assign its position
self.obs[0].r = {'x': 100.0, 'y': 38.0, 'z': -42.0}
# Append second particle
self.obs.append(particle())
# Assign second position
self.obs[1].r = {'x': 0.01, 'y': 99.0, 'z': 32.0}
#if you want to call getobs from here use :
#self.getobs1()
def getobs0(self):
print(self.obs[0].r)
def getobs1(self):
print(self.obs[1].r)
if __name__ == '__main__':
myClass = Myclass() #create an object of Myclass and call __init__()
myClass.getobs0()
myClass.getobs1()
Upvotes: 1