pythonoop

Python function not accepting state variables


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


Solution

  • 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.