通过字典的一个人的功能和属性

2024-04-24 14:07:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很难理解函数,以及如何使用它们来创建属性(在这个例子中,我的任务是与一个人)

下面是我在字典中声明人物的代码

def format(person):
    return "Name:\t" + person['name']

def display(person):
    print(format(person))

person = {'name':"Bilbo Baggins"}

然后我可以调用显示器来产生

Name = Bilbo Baggins

然后,我必须在字典中添加一个属性来存储我的人的体重和身高(假设现在两者都是0),我已经这样做了

person['height'] = 0
person['weight'] = 0

我现在需要创建一个函数(名为create\u person),其中包含3个参数(name、height和weight),并修改我以前的代码以使用此函数,同时打印name:Bilbo Baggins还打印weight(以kg为单位)和height(以m为单位)。你知道吗

总体目标是找出一个人的BMI,BMI是通过体重/身高2来计算的。我还需要添加一个函数,该函数将上一个字典/函数中的单个person对象作为参数,并返回person的BMI。把两者联系起来有可能吗?你知道吗


Tags: 函数代码nameformat字典属性defperson
1条回答
网友
1楼 · 发布于 2024-04-24 14:07:04
class Person:
    def __init__(self, name, height, weight):
        self.name = name
        self.height = height
        self.weight = weight
    # This is called when you print(PERSON OBJECT)
    def __repr__(self):
        return self.name + " " + self.height + " " + self.weight
    def BMI(self):
        return (self.weight/self.height)/self.height

这允许您创建这样一个人:

person_one = Person("Bilbo", 177, 72.7)
print(person_one)
bmi = person_one.BMI()

相关问题 更多 >