1.声明一个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
class Computer:
def __init__(self,brand='神舟',color='七彩色',memsize='512TB'):
self.brand = brand
self.color = color
self.memsize = memsize
def __repr__(self):
return '<' + str(self.__dict__)[1:-1] + ' at ' + hex(id(self)) + '>'
def game(self):
print('%s可以打游戏' % self)
def game(self):
print('%s可以写代码' % self)
def game(self):
print('%s可以看视频' % self)
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
c1 = Computer()
print('==================获取================')
# 获取c1的品牌信息
print(c1.brand)
print('==================修改================')
# 把c1的品牌修改为Mac
c1.brand = 'Mac'
print('==================添加================')
# 添加c1的显卡属性,是2080Ti
c1.gpu = '2080Ti'
print('==================删除================')
# 删除c1的颜色属性
del c1.color
b.通过attr相关方法去获取、修改、添加和删除它的属性
c1 = Computer()
print('==================获取================')
# 获取c1的品牌信息
getattr(c1,'brand')
print('==================修改================')
# 把c1的品牌修改为Mac
setattr(c1,'brand','Mac')
print('==================添加================')
# 添加c1的显卡属性,是2080Ti
setattr(c1,'gpu','2080Ti')
print('==================删除================')
# 删除c1的颜色属性
delattr(c1,'color')
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
class Dog:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def call(self):
print('%s在叫,喵' % self.name)
class Person:
def __init__(self,name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
print('%s在遛%s' % (self.name,self.dog))
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
p1 = Person('小明', 10, '大黄')
p1.walk_the_dog()
3.声明一个圆类:
class Circle:
def __init__(self, radius):
self.radius = radius
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
class Student:
def __init__(self,name, age, id):
self.name = name
self.age = age
self.id = id
def ask_dao(self):
print('点到')
print('%s' % self.name)
print('到!')
def __repr__(self):
return '✪' + str(self.__dict__)[1:-1] + ' at ' + hex(id(self)) + '✪'
s1 = Student('lilei', 12, 7651)
s1.ask_dao()
print(s1)
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Class:
# 声明班级类
def __init__(self, class_name, student = []):
self.class_name = class_name
self.student = student
# 用学生类给班级类的学生赋值
def add_stu(self, name, age, id, score):
stu = Student(name, age, id, score)
self.student.append(stu)
# 删除学生
def del_stu(self,name):
for stu in self.student:
if name == stu.name:
self.student.remove(stu)
return
else:
print('没有该学生')
return
# 班上学生的平均年龄
def average_age(self):
sum = 0
for stu in self.student:
sum += stu.age
average_age = sum/len(self.student)
print(average_age)
c1 = Class(1809)
c1.add_stu('lilei', 12, 7651, 80)
c1.add_stu('hanmeimei', 11,7652,41)
print(c1.student)
c1.del_stu('lilei')
print(c1.student)
c1.average_age()
网友评论