gpt4 book ai didi

python - 如何在类中的方法中正确运行方法(python)

转载 作者:太空宇宙 更新时间:2023-11-04 02:03:42 26 4
gpt4 key购买 nike

def main():

class BMI:

def __init__(self, firstName, lastName, age, height, weight):
self.firstName = firstName
self.lastName = lastName
self.fullName = firstName + " " + lastName
self.age = age
self.height = (height * 0.025) ** 2
self.weight = weight * 0.45

def setFullName(self, firstName, lastName):
self.firstName = firstName
self.lastName = lastName
self.fullName = firstName + " " + lastName

print(self.fullName)

def setAge(self, age):
self.age = age

def setHeight(self, height):
self.height = (height * 0.025) ** 2

def setWeight(self, weight):
self.weight = weight * 0.45

def getBMI(self):
bmi = self.weight // self.height
return bmi

def getStatus(self):

getBMI()

if bmi < 19:
print("You have an unhealthy BMI, gain some weight!")
elif bmi > 19 and bmi < 25:
print("You have a healthy BMI")
else:
print("You have an unhealthy BMI, lose some weight!")


firstName = input("Enter your first name: ")

lastName = 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: "))

userInputBMI = BMI(firstName, lastName, age, height, weight)


print(userInputBMI.setFullName(firstName, lastName))

print("Your BMI is:", userInputBMI.getBMI())

print(userInputBMI.getStatus())

主要()

我的问题是根据用户提供的输入打印用户的状态。问题出在“getStatus”方法中运行的方法。

我的想法是,从“getStatus”中的那个方法,它获得了在 if-elif-else 语句中测量的 bmi。计算机说“getBMI”未定义。如果有人能教我正确的方法来使用我正在尝试的方法,那就太棒了!

最佳答案

您需要告诉 Python,在您的 getStatus 方法中,您想从同一个类访问您的 getBMI 方法,而不是一个函数(或任何其他可调用的object) 名为 getBMI 的对象,它是在您的类之外定义的。您可以通过在类中将该方法引用为 self.getBMI 来执行此操作,如下所示:

def getStatus(self): 

bmi = self.getBMI()

请注意,我还捕获了 getBMI 的返回值,否则该值将丢失。 bmi 只是 getBMI 方法中的一个局部变量,一旦它结束就会被遗忘,除非你:

  • 返回该值并在执行该方法时用另一个变量捕获返回值;
  • 将其保存为实例属性,在您的 getBMI 方法中写入(在某些时候)self.bmi = bmi

我会选择第一个选项,因为名为 getBMI 的方法返回 bmi 是有意义的。如果您不断地编写和重写实例属性,也更容易弄乱并忘记哪个属性是哪个 - 虽然有时这正是您首先使用对象和类的原因。

关于python - 如何在类中的方法中正确运行方法(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55192966/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com