You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python类方法未接收状态变量引发变量未定义问题求助

解决Python类方法中变量未定义的问题

你的update方法存在两个核心问题,导致了变量未定义的报错:

  1. 实例方法缺少self参数:Python中类的实例方法必须以self作为第一个参数,它用来指代当前类的实例,没有这个参数就无法访问实例的属性。
  2. 未通过self引用实例属性:直接写velocity、acceleration时,Python会把它们当成局部变量,但你并没有在方法内定义这些局部变量,所以会提示未定义。

修正后的代码如下:

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(self):
        # 通过self访问实例属性,并更新值
        self.velocity = self.velocity.add(self.acceleration)
        self.position = self.position.add(self.velocity)

关键修正说明

  • 给update方法添加self参数,这是访问实例属性的必要前提
  • 所有需要访问的实例属性都加上self.前缀,比如self.velocity、self.acceleration,这样才能正确调用初始化时赋值的实例变量
  • 计算后的结果要重新赋值给self.velocity和self.position,否则实例的状态不会被更新

内容的提问来源于stack exchange,提问作者CJ Uldrich

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.12 01:25:55