"""author = Zard"""
1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的
class Computer:
"""电脑类"""
def __init__(self,brand,color,ram):
self.brand = brand
self.color = color
self.ram = ram
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def watch_video(self):
print('看视频')
def __repr__(self):
return '<%s>' % str(self.__dict__)[1:-1]
com1 = Computer('lenovo','black','8G')
com1.screen = '27寸'
com1.color = 'white'
del com1.ram
print(com1)
getattr(com1,'color')
setattr(com1,'screen','30寸')
delattr(com1,'brand')
print(com1)
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
"""狗 类"""
def __init__(self,name,color='red',age=5):
self.name = name
self.color = color
self.age = age
def call(self):
print('%s 在叫唤'% self.name)
class Person:
"""人 类"""
def __init__(self,name,age=15):
self.name = name
self.dog = None
self.age = age
def walk_dog(self,dog):
if not self.dog:
print('没有狗!遛自己。。')
else:
print('%s 在遛 %s' % (self.name,self.dog.name))
# 创建人对象
p1 = Person('小明')
# 创建狗对象
dog1 = Dog('大黄',15)
p1.dog = dog1
print(p1.walk_dog())
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
"""圆 类"""
pi = 3.1415926
def __init__(self,r):
self.r = r
def area(self):
return pi * self.r**2
def perim(self):
return 2*pi*self.r
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建⼀一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
"""学生类"""
def __init__(self,name,age=18,study_id=0):
self.name = name
self.age = age
self.study_id = study_id
def answer(self):
return '%s 答到!' % self.name
def show(self):
print('姓名:%s,年龄:%s,学号:%s' % (self.name,self.age,self.stud_yid))
class Class:
"""班级类"""
def __init__(self,name):
self.student = []
self.name = name
def func():
num = 1
while True:
yield 'stu'+str(num)
num += 1
self.creat_id = func()
def add_student(self):
name = input('请输入学生姓名:')
age =int( input('请输入学生年龄:'))
study_id = next( self.creat_id)
stu = student(name,age,study_id)
self.student.append(stu)
def show_all_student(self):
print('%s的学生' % self.name)
for stu in self.student:
stu.show()
def del_student(self):
del_name = input('请输入需要删除的学生姓名:')
flag = False
for stu in self.student[:]:
if stu.name == del_name:
flag = True
stu.show()
value = input('是否删除(y/n):')
if value == 'y':
self.student.remove(stu)
if not flag:
print('没有该学生!')
def call_name(self):
for stu in self.student:
stu.show()
stu.answer()
def avg_age():
ages = 0
for stu in self.student:
ages += stu.age
return ages/len(self.student)