1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
class computer:
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play_game(self):
return self.memory + '的电脑用来打游戏很流畅'
def write_code(self):
return self.brand + '牌的电脑可以用来写代码'
def watch_film(self):
return self.color + '的电脑晚上可以营造看鬼片的氛围'
computer1 = computer('华为', '黑色', '内存大')
print(computer1.play_game())
print(computer1.write_code())
print(computer1.watch_film())
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
获取
print(computer1.memory)
修改
computer1.memory = '内存小'
print(computer1.memory)
添加
computer1.shape = '笔记本'
print(computer1.shape)
删除
del computer1.shape
# print(computer1.shape) #AttributeError: 'computer' object has no attribute 'shape'
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
获取
print(getattr(computer1,'color'))
修改
setattr(computer1, 'memory', 'xiao')
print(computer1.memory)
添加
setattr(computer1, 'shape', '笔记本')
print(computer1.shape)
删除
delattr(computer1, 'shape')
# print(computer1.shape) #AttributeError: 'computer' object has no attribute 'shape'
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
class Dogs:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def cry_out(self):
return self.age + self.color + '的' + self.name + '叫唤着,像是在叫'
class Peoples:
def __init__(self, name, age):
self.name = name
self.age = age
def stroll(self):
return self.name + '带他出去溜溜弯儿'
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
people = Peoples('小明',18)
dog = Dogs('大黄', '黄色', '年轻的')
print(dog.cry_out() + people.stroll())
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Roundness:
def __init__(self,radius):
self.radius = radius
def area(self):
return self.radius * self.radius * 3.14
r = int(input('请输入圆的半径:'))
roundness = Roundness(r)
print('圆的面积为:',roundness.area())
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Students:
def __init__(self,name,age,num):
self.name = name
self.age = age
self.num = num
def respond(self):
return self.name + '站起来说:“我叫' + self.name + ' 今年' + self.age + '岁,' + '我的学号是' + self.num + '"。'
student = Students('小米', '13', '2019303234')
print(student.respond())
class Classes:
def __init__(self, class_name1, students1):
self.class_name = class_name1
self.students = students1
def add_student(self, name, age):
self.students.setdefault(name, age)
return students
def del_student(self, name):
del self.students[name]
return students
def aver_age(self, studentss):
self.student = studentss
sum = 0
count = 0
for key in studentss:
sum += studentss[key]
count += 1
return sum / count
students = {'詹三': 12, '李四': 34, '吴广': 23}
class1 = Classes('一班', students)
print(class1.add_student('喜洋洋', 24))
print(class1.del_student('喜洋洋'))
print(class1.aver_age(students))