1.声明一个电脑类: 属性:品牌、颜色、内存大小。方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand: str, color: str, memory_size: str):
self.brand = brand
self.color = color
self.memory_size = memory_size
def play_game(self):
print('打游戏!')
def write_code(self):
print('写代码!')
def watch_tv(self):
print('看电视!')
com1 = Computer('呆呆', '金', '8GB')
# a
# 1.获取品牌名
print(com1.brand)
# 2.修改成红色
com1.color = '红'
print(com1.color)
# 3.添加新属性:使用寿命
com1.life = 5
print('寿命:', com1.life)
# 4.删除属性:使用寿命
del com1.life
print(com1.__dict__)
# b
# 1.获取品牌名
name = getattr(com1, 'brand')
print(name)
# 2.修改成绿色
setattr(com1, 'color', '绿')
print(getattr(com1, 'color'))
# 3.添加新属性:使用寿命
setattr(com1, 'life', 10)
print(getattr(com1, 'life'))
# 4.删除属性:使用寿命
delattr(com1, 'life')
print(com1.__dict__)
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
def __init__(self, dog_name, color, age):
self.name = dog_name
self.color = color
self.age = age
def call_out(self):
print('汪汪汪')
class Person:
def __init__(self, p_name, age, dog):
self.name = p_name
self.age = age
self.dog = dog
def walk_dog(self):
print('{}正在遛{}'.format(self.name, self.dog))
p1 = Person('小明', 18, '大黄')
p1.walk_dog()
3.声明一个圆类,自己确定有哪些属性和方法
class Circular:
def __init__(self, radius):
self.radius = radius
def get_area(self):
return '%.2f' % (3.14*self.radius**2)
def get_peri(self):
return '%.2f' % (6.28*self.radius)
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
num = 1
def __init__(self, s_name, age):
self.name = s_name
self.age = age
self.sno = str(self.num).zfill(4)
self.__class__.num += 1
def answer(self, s_name):
if self.name == s_name:
print('到')
def show_student_info(self):
print('姓名:'+self.name, '年龄:', self.age, '学号:'+self.sno)
s1 = Student('鲁班', 5)
s2 = Student('娜可露露', 25)
s3 = Student('貂蝉', 20)
# 答到
s1.answer('鲁班')
# 展示学生信息
s3.show_student_info()
class Class:
sum = 0
def __init__(self, students: list, cname):
self.stu_dict = {}
self.students = []
self.students = students
self.cname = cname
def add_stu(self, s_name, sage):
self.stu_dict['姓名'] = s_name
self.stu_dict['年龄'] = sage
self.stu_dict['学号'] = str(int(self.students[-1]['学号'])+1).zfill(4)
self.students.append(self.stu_dict)
def delete_stu(self, sno):
for stu_dict in self.students:
if sno == stu_dict['学号']:
self.students.remove(stu_dict)
break
def roll_call(self):
for stu_dict in self.students:
print(stu_dict['姓名'])
def avg_age(self):
self.sum = 0
for stu_dict in self.students:
self.sum += stu_dict['年龄']
return '平均年龄:'+str(self.sum/len(self.students))
class1 = Class([{'姓名': '小乔', '年龄': 17, '学号': '0001'},
{'姓名': '王昭君', '年龄': 20, '学号': '0002'}], 'python1903')
# 添加学生:小红
class1.add_stu('小红', 10)
# 删除学生:'0003'
class1.delete_stu('0003')
# 点名
class1.roll_call()
# 求班上学生的平均年龄
print(class1.avg_age())