def main():
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
</dependency>
main()
我的问题是根据用户提供的输入来打印用户的状态。问题来自“ getStatus”方法中正在运行的方法。
我的想法是,从“ getStatus”中的该方法获取在if-elif-else语句中测量的bmi。计算机说“ getBMI”未定义。如果有人可以教我正确使用方法的方法,那真是太棒了!
答案 0 :(得分:1)
更改行:
getBMI()
到
bmi = self.getBMI()
我有多年的编程经验,但我也像您一样学习Python作为一种新语言。请纠正我的任何人,如果我错了或者您有什么要补充的。这是我对正确使用方法和语言的建议:
这是我以代码形式提出的建议(我故意留了一个bug-我认为这很容易捕获。很抱歉,如果不止一个,没有人是完美的):
class BodyMassIndex:
BMI_STATUS_LOSE = 0
BMI_STATUS_HEALTHY = 1
BMI_STATUS_GAIN = 2
def __init__(self, first_name, last_name, age, height, weight):
self._first_name = first_name
self._last_name = last_name
self._age = age
self._height = height
self._weight = weight
def get_full_name(self):
return self._first_name + " " + self._last_name
def get_bmi(self):
return (self._weight * 703) / self._height ** 2
def get_status(self):
bmi = self.get_bmi()
if bmi < 18.5:
status = BodyMassIndex.BMI_STATUS_LOSE
elif bmi < 25.0:
status = BodyMassIndex.BMI_STATUS_HEALTHY
else:
status = BodyMassIndex.BMI_STATUS_GAIN
return status
def get_report(self):
a = self.get_full_name()
b = "Your BMI is: {0:.1f}".format(self.get_bmi())
status_name = ['n unhealthy BMI, lose some weight!',
' healthy BMI',
'n unhealthy BMI, gain some weight!']
c = 'You have a' + status_name[self.get_status()]
return a + '\n' + b + '\n' + c
if __name__ == '__main__':
def first_test():
user_test_list = [
("Alex", "Fat", 21, 69, 170, 2),
("Josh", "Smart", 17, 69, 169, 1),
("Ann", "Full", 19, 69, 126, 1),
("Mary", "Skinny", 19, 69, 125, 0),
]
for first, last, age, height, weight, expected in user_test_list:
user = BodyMassIndex(first, last, age, height, weight)
print(user.get_report())
print()
first_test()
while True:
first = input("Enter your first name: ")
if not first:
break
last = input("Enter your last name: ")
age = int(input("Enter your age: "))
height = int(input("Enter your height in inches: "))
weight = int(input("Enter your weight in lbs: "))
user = BodyMassIndex(first, last, age, height, weight)
print(user.get_report())
答案 1 :(得分:1)
您需要告诉Python,在getStatus
方法内部,您想从同一类访问getBMI
方法,而不是名为{{1的函数(或任何其他可调用对象) }}是在课程之外定义的。您可以通过在类中将方法引用为getBMI
来完成此操作,如下所示:
self.getBMI
请注意,我还捕获了def getStatus(self):
bmi = self.getBMI()
的返回值,因为否则该值将丢失。 getBMI
只是bmi
方法内的局部变量,一旦结束,该变量将被遗忘,除非您执行以下任一操作:
getBMI
方法内写入(有时)self.bmi = bmi
。我会选择第一个选项,因为对于名为getBMI
的方法来说,返回bmi是有意义的。如果您不停地编写和重写实例属性,那么弄乱并忘记哪个属性是哪个属性也更容易-有时这正是您首先要使用对象和类的原因。