2

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!

2
  • 1
    I am almost certain you have this backwards. The first block of code might work, pretty sure the second one doesn't. Commented Mar 31, 2021 at 7:30
  • what was the result from the first code? Commented Mar 31, 2021 at 7:33

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.