用python自定义学生类Student, 成员包含:实例属性sno、sname、age,类属性count; 实例方法:show()用于显示sno、sname 、age的信息;类方法 classAddCount()实现count属性加1;静态 方法staticShowcount()显示当前count 值。要求属性全部为私有,完成下列问 颢• (1) 创建两个Student对象,分别 访问上述成员方法,同时用类名访问 上述成员方法,并输出结果。 (2)为Student对象动态增加新成员性别sex和方法setGrade()获取学生年级,导入types模块,调用 MethodType () 方法。 (3) 在类外部访问sno私有实例 厲性 (4) 请在类中提供get()方法返回age的值,以及set()方法设置age的新值。新age>0时,允许设置为新值,新age<=0时,提示设置年龄不合法。
时间: 2024-02-23 22:02:06 浏览: 22
好的,我来为你解答。
```python
import types
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("学号:{0},姓名:{1},年龄:{2}".format(self.__sno, self.__sname, self.__age))
@classmethod
def classAddCount(cls):
cls.count += 1
@staticmethod
def staticShowcount():
print("当前count值为:", Student.count)
def setGrade(self, grade):
self.__grade = grade
def get(self):
return self.__age
def set(self, age):
if age > 0:
self.__age = age
else:
print("设置年龄不合法!")
# 创建两个Student对象
stu1 = Student("1001", "张三", 18)
stu2 = Student("1002", "李四", 20)
# 访问实例方法
stu1.show()
stu2.show()
# 用类名访问实例方法
Student.show(stu1)
Student.show(stu2)
# 访问类方法
Student.classAddCount()
# 访问静态方法
Student.staticShowcount()
# 动态增加新成员sex和方法setGrade()
stu1.sex = "男"
stu1.setGrade = types.MethodType(lambda self, grade: setattr(self, "__grade", grade), stu1)
stu1.setGrade("大一")
print(stu1.sex)
print(stu1.__grade)
# 访问私有实例属性sno
print(stu1._Student__sno)
# 访问set()方法
stu1.set(25)
print("修改后的年龄为:", stu1.get())
stu1.set(-1)
```
输出结果如下:
```
学号:1001,姓名:张三,年龄:18
学号:1002,姓名:李四,年龄:20
学号:1001,姓名:张三,年龄:18
学号:1002,姓名:李四,年龄:20
当前count值为: 3
男
大一
1001
修改后的年龄为: 25
设置年龄不合法!
```
相关推荐
![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)
![](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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![application/x-rar](https://img-home.csdnimg.cn/images/20210720083606.png)