【问题标题】:Trying to print, but says my function name is not defined?试图打印,但说我的函数名没有定义?
【发布时间】:2017-04-20 09:06:52
【问题描述】:
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

【问题讨论】:

  • if self.getBMI() &lt; 18.5 等。使用self 来引用方法和属性,也在方法内部。
  • 旁注:由于您在句子下方放置了下划线,中间句子大而粗体,标记将其解释为header
  • @downshift 哦,我明白了,谢谢!
  • @TheIllusion 当然,如果您想编辑它,只需选择该句子并反复按“CTRL+H”即可获得所需的大小。为让您的代码正常工作而欢呼! :)

标签: python


【解决方案1】:

原因在于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? ")

【讨论】:

  • 确保在末尾包含return self.__getStatus 行。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-09-19
    • 1970-01-01
    • 1970-01-01
    • 2016-08-11
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多