编写程序,创建计算类,要求输入半径,计算圆的周长和面积,以及球的表面积和体积。 2、编写程序,创建 People 类,该类中包含三种属性:姓名、性别、年龄以及针对每个属性的 get 和 set 方法。创建 Student 类,继承自 People 类,添加额外三个属性:学号、班级和数量统计。 创建 Teacher 类,继承自 People 类,添加额外三个属性:工号、学院和数量统计。要求在 Student 类 和 Teacher 类中分别实现 printInfo 方法,该方法打印对象的多有属性信息。
时间: 2024-03-08 21:47:40 浏览: 79
1. 计算类计算圆周长、面积、球表面积和体积的程序:
```python
import math
class Calculation:
def __init__(self, radius):
self.radius = radius
def circle_perimeter(self):
return 2 * math.pi * self.radius
def circle_area(self):
return math.pi * self.radius ** 2
def sphere_surface_area(self):
return 4 * math.pi * self.radius ** 2
def sphere_volume(self):
return 4/3 * math.pi * self.radius ** 3
# 测试代码
calc = Calculation(5)
print("圆的周长为:{:.2f}".format(calc.circle_perimeter()))
print("圆的面积为:{:.2f}".format(calc.circle_area()))
print("球的表面积为:{:.2f}".format(calc.sphere_surface_area()))
print("球的体积为:{:.2f}".format(calc.sphere_volume()))
```
2. People、Student、Teacher 类的程序:
```python
class People:
def __init__(self, name, gender, age):
self.name = name
self.gender = gender
self.age = age
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
class Student(People):
count = 0
def __init__(self, name, gender, age, student_id, student_class):
super().__init__(name, gender, age)
self.student_id = student_id
self.student_class = student_class
Student.count += 1
def get_student_id(self):
return self.student_id
def set_student_id(self, student_id):
self.student_id = student_id
def get_student_class(self):
return self.student_class
def set_student_class(self, student_class):
self.student_class = student_class
def print_info(self):
print("姓名:{}\n性别:{}\n年龄:{}\n学号:{}\n班级:{}".format(
self.name, self.gender, self.age, self.student_id, self.student_class))
class Teacher(People):
count = 0
def __init__(self, name, gender, age, teacher_id, college):
super().__init__(name, gender, age)
self.teacher_id = teacher_id
self.college = college
Teacher.count += 1
def get_teacher_id(self):
return self.teacher_id
def set_teacher_id(self, teacher_id):
self.teacher_id = teacher_id
def get_college(self):
return self.college
def set_college(self, college):
self.college = college
def print_info(self):
print("姓名:{}\n性别:{}\n年龄:{}\n工号:{}\n学院:{}".format(
self.name, self.gender, self.age, self.teacher_id, self.college))
# 测试代码
s = Student("张三", "男", 20, "20190101", "计算机科学与技术")
s.print_info()
print("学生总数:{}".format(Student.count))
t = Teacher("李四", "女", 30, "10001", "计算机科学与技术")
t.print_info()
print("教师总数:{}".format(Teacher.count))
```
注意,在子类 Student 和 Teacher 中都添加了一个 count 类属性,用于统计创建的对象个数,这个属性在每个子类中都独立存在,不会相互影响。同时,在每个子类中都实现了 print_info 方法,用于打印对象的各个属性信息。
阅读全文