0
import Vector

class Ball:
    radius: float
    color: str

    position: Vector.Vector
    velocity: Vector.Vector
    acceleration: Vector.Vector

    def __init__(self, radius, color,position, velocity, acceleration):
        self.radius = radius
        self.color = color
        self.position = position
        self.velocity = velocity
        self.acceleration = acceleration

    def update():
        velocity = velocity.add(acceleration)
        position = position.add(velocity)

    

The problem I'm having is that the acceleration in the update function is registering that acceleration is a state variable, and it is saying it is not defined

3
  • About using 'self': stackoverflow.com/questions/2709821/… Commented Nov 16 at 1:13
  • about catching these problems in general: You should gear up with some linting in your editor. A linter can tell you that (1) acceleration is not defined and (2) your update-method is suspicious for not having self. Commented Nov 16 at 1:17
  • If you use a decent IDE to develop your code, you'll see lots of issues highlighted in your code. You definitely need to learn the difference between class and instance variables. We have no idea what the Vector module is Commented Nov 16 at 9:25

1 Answer 1

3

Ah, you're missing self in your update() method! That's why Python can't find your instance variables.

Your method should look like this:

def update(self):
    self.velocity = self.velocity.add(self.acceleration)
    self.position = self.position.add(self.velocity)

The problem is that instance methods in Python need self as the first parameter so they can actually access the object's attributes. Without it, when you write acceleration, Python's looking for a local variable called acceleration in the method, which doesn't exist.

You also need the self. prefix when you're accessing or modifying instance variables - otherwise you're just creating temporary local variables that disappear when the method ends, and your Ball's actual position and velocity never get updated.

New contributor
EchoOverflow is a new contributor to this site. Take care in asking for clarification, commenting, and answering. Check out our Code of Conduct.
Sign up to request clarification or add additional context in comments.

1 Comment

Please explain what the class variables are doing in the OP. Perhaps the intent was to update them in which case and instance method would not be needed

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.