python面向对象实验
1.定义一个学校人员类SchoolPerson,
2.在第1个题的基础上添加两个方法:
3.创建学生类Student,继承自SchoolPerson类,添加额外两个属性:班级class、学号sno。
4.在上一题的基础上定义学生类、教师类的对象,然后分别调用print_info方法,实现各自对象属性信息的输出。
5.创建类MyMath,计算圆的周长、面积和球的表面积、体积,结果保留两位小数。若输入的是非数字,则输出:请输入数字!提示:要引入math包。
在这里插入代码片
import math
# 实验1
class SchoolPerson:
def set_info(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
student = SchoolPerson()
student.sex = "男"
student.age = "18"
student.name = "张三"
student1 = SchoolPerson()
student1.sex = "女"
student1.age = "18"
student1.name = "李四"
print("")
print("学生姓名:" + student.name + " 学生年龄:" + student.age + " 学生性别:" + student.sex)
print("学生姓名:" + student1.name + " 学生年龄:" + student1.age + " 学生性别:" + student1.sex)
print("")
# 实验二
class SchoolPerson1:
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def __del__(self):
print("实例对象已经删除")
def set_info(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
student2 = SchoolPerson1("张三", "男", "18")
student3 = SchoolPerson1("李四", "女", "18")
print("")
print("学生姓名:" + student2.name + " 学生年龄:" + student2.age + " 学生性别:" + student2.sex)
print("学生姓名:" + student3.name + " 学生年龄:" + student3.age + " 学生性别:" + student3.sex)
print("")
# 实验三,实验四
class SchoolPerson2:
def __init__(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def __del__(self):
print("实例对象已经删除")
def set_info(self, name, sex, age):
self.name = name
self.sex = sex
self.age = age
def get_info(self):
return self.name + " " + self.sex + " " + self.age
class Student(SchoolPerson2):
def __init__(self, name, sex, age, class0, sno):
super(Student, self).__init__(name, sex, age)
self.class0 = class0
self.sno = sno
def print_info(self):
print(self.name + " " + self.sex + " " + self.age + " " + self.class0 + " " + self.sno)
class Teacher(SchoolPerson2):
def __init__(self, name, sex, age, department, cno):
super(Teacher, self).__init__(name, sex, age)
self.department = department
self.cno = cno
def print_info(self):
print(self.name + " " + self.sex + " " + self.age + " " + self.department + " " + self.cno)
student4 = Student("张三", "男", "18", "移动四班", "234345645")
student4.print_info()
student5 = Teacher("帅帅", "男", "28", "辅导员", "234345456534")
student5.print_info()
# 实验五
class MyMath:
def __init__(self, r):
self.r = r
def jie_guo(self):
print("园的周长:", 2*self.r*math.pi)
print("园的面积:" ,self.r*self.r*math.pi )
print("园的体积:" ,(4/3)*math.pi*self.r*self.r*self.r)
try:
r = int(input("请输入半径:"))
lll = MyMath(r)
lll.jie_guo()
except:
print("r为数字")
math包引入
File ->Setting -> Project:sy python ->Python Interpreter
有numpy就是了,没有就点右上角+号搜numpy然后下载