试图打印,但说我的函数名称没有定义?

时间:2016-12-05 21:03:45

标签: python

name = str(input("What is your name? "))
age = int(input("What is your age? "))
weight_float = float(input("What is your weight in pounds? "))
height_float = float(input("What is your height in inches? "))

Pounds2Kilogram = weight_float * 0.453592
Inches2Meter = height_float * 0.0254

weight = Pounds2Kilogram
height = Inches2Meter


class calcBMI:

    def __init__(self, name, age, weight, height):
        self.__name = name
        self.__age = age
        self.__weight = weight
        self.__height = height

    def getBMI(self):
        return self.__weight / (self.__height **2)

    def getStatus(self):
        if getBMI() < 18.5:
            self.__getStatus = "Underweight"
        elif 18.5 < getBMI() < 24.9:
            self.__getStatus = "Normal"
        elif 25.0 < getBMI() < 29.9:
            self.__getStatus = "Overweight"
        elif getBMI() > 30:
            self.__getStatus = "Obese"

    def getName(self):
        return self.__name

    def getAge(self):
        return self.__age

    def getWeight(self):
        return self.__weight

    def getHeight(self):
        return self.__height


a = calcBMI(name, age, weight, height)     
print("The BMI for ", a.getName(), " is ", a.getBMI(), "which is ", a.getStatus())

我尝试打印这个BMI计算器时遇到了一些问题,最后看起来应该是这样的,

“(姓名)的BMI是(BMI号码),这是(状态,基本上如果他们体重不足,超重等)。”

在getStatus()中,我试图从getBMI()获取数值并在if语句中使用它。 (我不知道为什么这个大而大胆的字母)

当我尝试打印时出现问题,它会提示我像平常一样输入我的姓名,年龄,体重和身高。

这是它输出的内容: NameError: name 'getBMI' is not defined

2 个答案:

答案 0 :(得分:2)

原因是在getStatus函数中,您正在调用getBmi,但您应该调用self.getBmi()

getStatus函数应如下所示:

def getStatus(self):
    if self.getBMI() < 18.5:
        self.__getStatus = "Underweight"
    elif 18.5 < self.getBMI() < 24.9:
        self.__getStatus = "Normal"
    elif 25.0 < self.getBMI() < 29.9:
        self.__getStatus = "Overweight"
    elif self.getBMI() > 30:
        self.__getStatus = "Obese"
    return self.__getStatus

此外,当input自动返回字符串时,您可以说

name = input("What is your name? ")

答案 1 :(得分:0)

getBMI未定义为全局函数,因此当您尝试将其称为NameError时,会引发getBMI。这个名称的方法不能像C ++方法那样赤裸裸地引用。相反,实例必须将其方法称为self的属性,即在这种情况下为self.getBMI()