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

Python实现BMI计算功能运行报TypeError缺失height参数原因求助

错误原因排查及修复方案
  • 实例方法调用规则错误
    你定义的calc_bmi是类的实例方法,第一个固定参数self需要接收实例对象本身。你代码中使用类名bmi直接调用方法,传入的weight会被识别为self参数,height会被识别为方法需要的weight参数,最终导致方法要求的第三个参数height没有传值,触发参数缺失报错。
    修复方案:将调用代码改为用你已经实例化得到的obj对象调用方法,self参数会由Python自动传入,不需要手动赋值:
result = obj.calc_bmi(weight,height)
  • 计算逻辑错误
  1. 方法内部你使用了self.weight和self.height,这两个是类初始化时设置的默认值0,没有用到你传入的用户输入值
  2. BMI计算公式错误,正确公式为体重÷(身高的平方),你写的self.weight /self.height * self.height计算结果等价于self.weight,完全不符合BMI计算规则
    修复方案:修改calc_bmi方法的实现:
def calc_bmi(self,weight,height):
    bm = weight / (height ** 2)
    return bm

完整修正后代码

class bmi:
    def __init__(self):
        self.weight = 0
        self.height = 0

    def calc_bmi(self,weight,height):
        bm = weight / (height ** 2)
        return bm

def main():
    obj = bmi()
    weight = float(input("Enter weight"))
    height = float(input("Enter height"))

    result =  obj.calc_bmi(weight,height)
    print(f"Your bmi is {result:.2f}")

main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 00:54:06