定义学生类Student,成员包含:对象属性:sno、sname、age,类属性count,对象方法show(),用于显示学生信息;类方法addCount(),实现count属性累加1,静态方法showCount(),用于显示count的值。要求所有 属性全部为私有。要求完成以下操作: (1)创建两个学生对象,输出学生基本信息,实现学生对象的累加,输出学生人数。 (2)为第一个学生对象动态添加属性sex(性别)和方法getName()(用于获取学生的姓名),输出学生的姓名和性别。
时间: 2023-10-07 07:12:15 浏览: 112
以下是实现上述要求的代码:
```python
class Student:
count = 0 # 类属性
def __init__(self, sno, sname, age):
self.__sno = sno # 私有属性
self.__sname = sname # 私有属性
self.__age = age # 私有属性
Student.count += 1 # 对象属性
def show(self):
print("学号:", self.__sno)
print("姓名:", self.__sname)
print("年龄:", self.__age)
@classmethod
def addCount(cls):
cls.count += 1
@staticmethod
def showCount():
print("学生人数:", Student.count)
# 创建两个学生对象并输出基本信息
stu1 = Student("001", "张三", 18)
stu2 = Student("002", "李四", 19)
stu1.show()
stu2.show()
# 输出学生人数
Student.showCount()
# 为第一个学生对象动态添加属性和方法
stu1.__sex = "男" # 动态添加私有属性
def getName(self): # 动态添加方法
return self.__sname
stu1.getName = getName.__get__(stu1, Student) # 绑定方法
print("姓名:", stu1.getName())
print("性别:", stu1._Student__sex) # 访问私有属性
```
输出结果为:
```
学号: 001
姓名: 张三
年龄: 18
学号: 002
姓名: 李四
年龄: 19
学生人数: 2
姓名: 张三
性别: 男
```
注意,动态添加的私有属性和方法的访问方式与普通私有属性和方法的访问方式略有不同,需要加上类名或者对象名前缀。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![apk](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)