对人类属性进行封装:1)定义一个类 Person; 2) 在类中定义属性: 姓名、性别、年龄、学历、身高。 3)对属性实现封装,并编写各属性的读写访问器。对属性中的年龄进行控制,要求年龄大于 0,否则使用默认值代替 (年龄默认 18)。 4)在类中定义 show (,功能为输出属性信息。5)在main 方法中实例化2个对象,通过读写访问器完成对属性的赋值和输出操作
时间: 2023-05-28 15:04:58 浏览: 212
class Person:
def __init__(self, name='', gender='', age=18, education='', height=0):
self.__name = name
self.__gender = gender
self.__age = age if age > 0 else 18
self.__education = education
self.__height = height
def get_name(self):
return self.__name
def set_name(self, name):
self.__name = name
def get_gender(self):
return self.__gender
def set_gender(self, gender):
self.__gender = gender
def get_age(self):
return self.__age
def set_age(self, age):
self.__age = age if age > 0 else 18
def get_education(self):
return self.__education
def set_education(self, education):
self.__education = education
def get_height(self):
return self.__height
def set_height(self, height):
self.__height = height
def show(self):
print(f'Name: {self.__name}\nGender: {self.__gender}\nAge: {self.__age}\nEducation: {self.__education}\nHeight: {self.__height}')
person1 = Person()
person1.set_name('Tom')
person1.set_gender('Male')
person1.set_age(25)
person1.set_education('Bachelor')
person1.set_height(180)
person2 = Person('Lucy', 'Female', 30, 'Master', 165)
person1.show()
print()
person2.show()
阅读全文