day12作业
-
声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性class Computer: def __init__(self, brand, color='black', size='16G'): self.brand = brand self.color = color self.size = size def play(self): print('play') def coding(self): print('coding') def mv(self): print('mv') # a. c1 = Computer('华为') print(c1.brand) c1.brand = 'apple' c1.screen = '14' del c1.screen # b. getattr(c1, 'brand') setattr(c1, 'size', '32G') setattr(c1, 'screen', '14') delattr(c1, 'screen')
-
声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄class Person: def __init__(self, name, age, dog): self.name = name self.age = age self.dog = dog def dogging(self): print('遛狗:', self.dog) class Dog: def __init__(self, name, color, age): self.name = name self.age = age self.color = color def bark(self): print('叫唤') d1 = Dog('大黄', '黄色', 2) p1 = Person('小明', '20', d1.name) p1.dogging()
-
声明⼀一个圆类,自己确定有哪些属性和方法
class Circle: pi = 3.1415926 def __init__(self, r): self.r = r def area(self): print('圆的面积:', self.pi * self.r ** 2) c1 = Circle(2) c1.area()
-
创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄class Student: def __init__(self, name, age, sid): self.name = name self.age = age self.sid = sid def answer(self): print('答到:', self.name) def msg(self): print('学生信息:', self.name, self.age, self.sid) """ class_name = [ {'sname':sname,'age':age,'sid':sid} ] """ class Clazz: def __init__(self, name: str): self.name = name self.stus = [] def add(self, stu): self.stus.append(stu) def _delete(self,stu): self.stus.remove(stu) def check(self): for stu in self.stus: yield stu['name'] def avg(self): sum1 = 0 for stu in self.stus: sum1 += stu['age'] avg = sum1 / len(self.stus) return avg s1 = Student('1', 20, '001') s2 = Student('2', 28, '002') c1 = Clazz('c1') c1.add(s1.__dict__) c1.add(s2.__dict__) print(c1.stus) print(c1.avg())