构造Person类。包括姓名(name),性别(sex)和年龄(age)。提供所有属性的set和get函数,提供print函数打印其信息
时间: 2023-07-14 09:11:57 浏览: 102
以下是用Python实现的Person类:
```python
class Person:
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def get_name(self):
return self.name
def set_name(self, name):
self.name = name
def get_sex(self):
return self.sex
def set_sex(self, sex):
self.sex = sex
def get_age(self):
return self.age
def set_age(self, age):
self.age = age
def print_info(self):
print("Name: {}\nSex: {}\nAge: {}".format(self.name, self.sex, self.age))
```
我们通过构造函数`__init__()`初始化对象的三个属性,通过`get`和`set`方法获取和设置属性值,通过`print_info()`函数打印属性信息。例如,我们可以这样使用它:
```python
person1 = Person("Alice", "female", 25)
person1.print_info()
person1.set_age(30)
person1.print_info()
```
输出:
```
Name: Alice
Sex: female
Age: 25
Name: Alice
Sex: female
Age: 30
```
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cs](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)