Python帮助将对象打印到字符串

时间:2016-12-04 03:00:03

标签: python

所以我有一个很直接的项目。这是一个简单的BMI计算器,应该只是打印,

“(姓名)的BMI是(BMI),(状态,如果他们体重不足,超重等)。

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 BMI < 18.5:
            self.__getStatus = "Underweight"
        elif 18.5 < BMI < 24.9:
            self.__getStatus = "Normal"
        elif 25.0 < BMI < 29.9:
            self.__getStatus = "Overweight"
        elif BMI > 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

    def __str__(self):
        return "The BMI for", + self.__name(), + "is", + self.__getBMI()

    def PrintBMI(self):
        print(self.__str__())

a = caclBMI     
print(a)

我一直在:

 <class '__main__.calcBMI'>

我知道这意味着我需要将对象转换为字符串,我确信我错过了一些简单的东西。

如果您愿意,请选择帮助。

4 个答案:

答案 0 :(得分:1)

a = caclBMI

你已经在课堂上反弹a了。您需要实例化该类。

答案 1 :(得分:0)

只需实施__str____repr__方法。

https://docs.python.org/3/reference/datamodel.html#object.str

https://docs.python.org/3/reference/datamodel.html#object.repr

class calcBMI:
    def __str__(self):
        return "The BMI for {} is {}".format(self.__name, self.getBMI())

    def __repr__(self):
        return 'calcBMI({}, {}, {), {})'.format(self.__name, self.__age, self.__height, self.__weight)

...

a = calcBMI("Zogzog", 123, 210, 176)
print(a)

答案 2 :(得分:0)

看起来你实际上并没有实例化对象。您需要实例化CalcBMI

的实例
...

my_calc_bmi = CalcBMI(my_name, my_age, ...)
print "String representation is: ", my_calc_bmi
print "Or converting explicitly: %s" % (str(my_calc_bmi))

答案 3 :(得分:0)

您在以下方法中遇到问题:

def __str__(self):
        return "The BMI for " + self.__name + " is " + str(self.getBMI())

由于self.getBMI()返回float值,您需要将其转换为string

此外,您需要实例化该类,如下所示:

a = caclBMI(name, age, weight, height)

例如:

a = calcBMI('Alex', 25, 100, 60)
print(a)

输出:

The BMI for Alex is 0.027777777777777776