"""author= HuangZhong"""
1.声明⼀个电脑类:
属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
"""类:电脑
属性:品牌、颜色、内存
方法:打游戏、写代码、看视频
"""
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def wSee_video(self):
print('看视频')
c1 = Computer('dell', 'silver', 8)
print(c1.brand) # 查看
setattr(c1, 'memory', 16)
print(c1.memory)
setattr(c1, 'price', 5000)
print(c1.price)
c1.brand = '东芝'
print('品牌:', c1.brand) # 点方法修改
setattr(c1, 'brand', '联想') # attr方法修改
c1.price = 5000 # 点方法添加
setattr(c1, 'screen', '15.4') # attr 方法添加
print('品牌:', c1.brand, '颜色:', c1.color, '内存:', c1.memory,
'价格:', c1.price, '屏幕尺寸:', c1.screen)
del c1.brand
delattr(c1, 'color')
print('内存:', c1.memory, '价格:', c1.price, '屏幕尺寸:', c1.screen)
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
"""类的说明:定义人类"""
def __init__(self, name, dog, age=0):
self.name = name
self.age = age
self.dog = dog
def playDog(self):
print('%s有一条叫做%s的狗,小明每天带着%s去遛弯' % (self.name, self.dog, self.dog))
class Dog:
"""类的说明:定义狗类"""
def __init__(self, name, color='黑色', age=1):
self.name = name
self.color = color
self.age = age
def bark(self):
print('%s天天叫唤个不停')
dog1 = Dog('大黄')
p1 = Person('小明', dog1.name)
p1.playDog()
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
"""类的说明:定义一个圆类,并求圆的周长和面积"""
global pi
pi = 3.14
def __init__(self, r):
self.r = r
def perimeter(self):
rerimeter = 2 * pi * self.r
return rerimeter
def area(self):
area = pi * self.r**2
return area
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
class Student:
"""类的说明:定义一个学生类"""
def __init__(self, name, age, stuid='001'):
self.name = name
self.age = age
self.stuid = stuid
self.state = random.randint(0, 1)
def answer(self):
if self.state == 0:
print('%s没有到' % self.name)
else:
print('%s 到了' % self.name, '姓名:%s 年龄:%s 学号:%s' % (self.name, self.age, self.stuid))
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Class:
"""
类的说明:定义一个班级类
实现添加学生,删除学生并且求出学生平均年龄的功能
"""
def __init__(self, class_name, *student):
self.class_name = class_name
self.student = list(student)
def add_student(self, stu):
self.student.append(stu)
def del_student(self, student):
self.student.remove(student)
def answer_student(self):
for stu in self.student:
stu.answer()
def avg_age(self):
totals = 0
for stu in self.student:
totals += stu.age
avg_age = totals / len(self.student)
return avg_age