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

Python类中调用__init__定义的weight参数报AttributeError问题排查

错误原因

  • 带self参数的方法是类的实例方法,必须通过类的实例调用,不能直接用类名调用。你写的Person.go_in(13,20,1)属于直接用类调用方法,此时你传入的第一个参数13会被自动赋值给self,整数类型的13不存在weight属性,因此触发属性错误。
  • __init__是类的实例初始化方法,只有在创建类实例的时候才会自动执行,你没有先完成Person类的实例化操作,自然没有地方存储weight参数,也无法从实例中读取该值。

修正方案

你需要先实例化Person类传入weight参数,再通过实例调用go_in方法传入age和height参数,正确代码如下:

class Person:
    def __init__(self, weight):
        self.weight = weight

    def go_in(self, age, height):
        enter_to_disco = age * height * self.weight
        if enter_to_disco < 10:
            print('enter to disco')
        else:
            print(f'do not enter to disco')


# 实例化Person类,传入weight参数
peter = Person(1)
# 通过实例调用go_in方法,传入age和height参数
peter.go_in(13, 20)

运行上述代码输出结果为:do not enter to disco

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.23 19:36:00