1.声明一个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关的方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand ='', color='', ram='0G'):
self.brand = brand
self.color = color
self.ram = ram
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def look_video(self):
print('看视频')
c1 = Computer('戴尔', '黑色', '8G')
print(c1.brand)
c1.price = 7000
print(c1.price)
c1.ram = '16G'
print(c1.ram)
print(getattr(c1, 'brand', None))
setattr(c1, 'color', '白色')
print(c1.color)
setattr(c1, 'price', 7000)
print(c1.price)
del c1.color
print(c1.color) # AttributeError: 'Computer' object has no attribute 'color'
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年年龄
狗的方法:叫唤
人的属性:名字、年年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Person:
def __init__(self, name, age='18', dog='大黄'):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
return '%s在溜%s' % (self.name, self.dog)
class Dog:
def __init__(self, dog_name, dog_age=3, dog_color='黄色'):
self.dog_name = dog_name
self.dog_age = dog_age
self.dog_color = dog_color
def shout(self):
return '%s在叫唤' % self.dog_name
3.声明一个圆类:
class Circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14*(self.radius**2)
def perimeter(self):
return 2*3.14*self.radius
c1 = Circle(4)
print('面积:%s, 周长:%s' % (c1.area(), c1.perimeter()))
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Class:
def __init__(self, student, class1):
self.student = student
self.class1 = class1
def add_student(self):
while True:
name = input('姓名:')
age = int(input('年龄:'))
self.student = {'name': name, 'age': age}
self.class1.append(self.student)
if self.class1:
print('添加成功!')
print('1.继续 2.退出')
input_value = input('请选择(1-2):')
if input_value != '1':
break
else:
print('添加失败!')
return self.class1
def del_student(self):
print(self.class1)
name = input('请输入要删除的学生:')
for stu in self.class1[:]:
if name == stu['name']:
self.class1.remove(stu)
break
else:
print('没有此学生!')
return self.class1
def answer(self):
for stu in self.class1:
print('姓名:%s 年龄:%d' % (stu['name'], stu['age']))
def avg_age(self):
sum1 = 0
for stu in self.class1:
sum1 += stu['age']
return '平均年龄:%s' % sum1/len(self.class1)
s1 = Student('张三', 23, 'stu01')
print(s1.answer())
c2 = Class({}, [])
print(c2.add_student())
c2.answer()
print(c2.avg_age())
print(c2.del_student())