1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, trademark='戴尔', color = '红色', memory = '8g'):
self.trademark = trademark
self.color = color
self.memory = memory
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def look_vide(self):
print('看电视')
computer = Computer()
print(computer.play_game())
print(computer.look_vide())
print(computer.write_code())
#获取
print(computer.color)
print(getattr(computer, 'color', 'zhl'))
#修改
computer.color = '黄色'
print(computer.color)
setattr(computer, 'memory', '10g')
print(computer.memory)
#添加
computer.color1 = '绿色'
print(computer.color1)
setattr(computer, 'color2', '黑色')
print(computer.color2)
#删除
del computer.color
print(computer.color)
delattr(computer, 'color')
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
def __init__(self, name, dog, age = '20'):
self.name = name
self.age = age
self.dog = dog
def play_dog(self, color):
print('%s去遛一条%s狗,他的名字叫做%s' %(self.name, color, self.dog))
class Dog:
def __init__(self, name = '大黄', color = '黄色', age = '5'):
self.name = name
self.color = color
self.age = age
def bark(self):
print('狗狗汪汪的叫')
dog1 = Dog()
person = Person('小明', dog1.name)
person.play_dog(dog1.color)
3.声明⼀一个矩形类:
属性:长,宽 方法:计算周长和面
a.创建不同的矩形,并且打印其周长长和面积
class Shape:
def __init__(self,length, width):
self.length = length
self.width = width
def perimeter(self):
return (self.width + self.length) * 2
def area(self):
return self.length * self.width
s1 = Shape(3, 4)
c = s1.perimeter()
area = s1.area()
print(c, area)
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student:
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = number
def answer(self):
print('%s到' %(self.name))
def display(self):
dict1 = {'学生':self.name, '年龄':self.age,'学号':self.number}
return dict1
class Lesson:
def __init__(self, student, class_name):
self.student = student
self.class_name = class_name
def add_student(self, *dict1):
list1 = []
list1.append(dict1)
return list1
def average(self, list1 ):
sum = 0
for i in list1:
for j in i:
sum +=int(j['年龄'])
return sum / (len(list1))
stu1 = Student('周海龙', '20', '001')
stu2 = Student('张程', '10', '002')
stu1.answer()
lesson = Lesson(stu1.name, '1班')
lesson.add_student(stu1.display(), stu2.display())
lesson.add_student(stu1.display(), stu2.display())
print(lesson.add_student(stu1.display(), stu2.display()))
num = lesson.average(lesson.add_student(stu1.display(), stu2.display()))
print(num)