Python 类与对象:创建 Person 类并实现自我介绍
class Person:
def __init__(self, name, height, weight):
self.name = name
self.height = height
self.weight = weight
def introduce(self):
print('My name is {}, my height is {} cm, my weight is {} kg.'.format(self.name, self.height, self.weight))
# 创建 person1 对象
name = input()
height = int(input())
weight = int(input())
person1 = Person(name, height, weight)
# 调用 introduce 方法进行自我介绍
person1.introduce()
在本代码中,我们定义了一个名为 'Person' 的类,它包含三个属性 'name'、'height' 和 'weight',以及一个名为 'introduce' 的方法。在主函数中,我们首先接收用户输入的姓名、身高和体重,并使用这些输入创建了一个 'Person' 对象 'person1'。最后,我们调用 'person1' 对象的 'introduce' 方法,使它进行自我介绍。
示例输入:
Bob
180
80
示例输出:
My name is Bob, my height is 180 cm, my weight is 80 kg.
原文地址: http://www.cveoy.top/t/topic/cj4b 著作权归作者所有。请勿转载和采集!