1.声明一个电脑类:属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取\修改\添加和删除它的属性
b.通过attr相关方法去获取\修改\添加和删除它的属性
class Computer:
def __init__(self, brand, color, memory=4):
self.brand = brand
self.color = color
self.memory = memory
def play_game(self, game):
print('用%s电脑玩%s' % (self.brand, game))
def write_code(self):
print('用%s电脑写代码' % self.brand)
def watch_video(self):
print('用%s电脑看视频' % self.brand)
computer1 = Computer('dell', 'black')
computer1.play_game('LOL')
computer1.CPU = 'i7 8500'
computer1.color = 'pink'
del computer1.CPU
print(getattr(computer1, 'brand', '没有品牌'))
setattr(computer1, 'memory', 8)
setattr(computer1, 'CPU', 'i7 8500')
delattr(computer1, 'CPU')
2.声明一个人的类和狗的类:
狗的属性:名字\颜色\年龄;狗的方法:叫唤
人的属性:名字\年龄\狗;人的方法:遛狗
a.创建人人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Person:
def __init__(self, name, age='', dog=None):
self.name = name
self.age = age
if dog:
self.dog = dog.name
else:
print('没有狗')
def walk_the_dog(self):
print('%s带着%s散步' % (self.name, self.dog))
class Dog:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def bark(self):
print('%s叫' % self.name)
dog1 = Dog('大黄', 'black', 4)
person = Person('小明', dog=dog1)
person.walk_the_dog()
3.声明一个圆类,自己确定有哪些属性和方法
import math
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return math.pi * self.r ** 2
def perimeter(self):
return math.pi*self.r*2
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名,求班上学生的平均年龄
class Students:
def __init__(self, name, age=None, student_numbers='0000'):
self.name = name
self.age = age
self.student_numbers = student_numbers
def answer_student(self):
print('%s在教室' % self.name)
print('1.在')
print('2.不在')
n = int(input('请输入:'))
if n == 1:
return True
else:
return False
def student_information(self):
print(self.name)
print(self.age)
print(self.student_numbers)
class Class:
def __init__(self, class_name, students_list: list):
self.class_name = class_name
self.students_list = students_list
def add_student(self):
name = input('请输入姓名')
age = int(input('请输入年龄'))
student_numbers = input('请输入学生学号')
stu = Students(name, age, student_numbers)
self.students_list.append(stu)
def del_student(self, name):
for index in range(len(self.students_list)):
if self.students_list[index].name == name:
self.students_list.remove(self.students_list[index])
break
def call_student(self):
for student in self.students_list:
if student.answer_student():
print('%s在' % student.name)
else:
print('%s不在' % student.name)
return
def average_age(self):
sum_age = 0
for student in self.students_list:
sum_age += student.age
return float(sum_age/len(self.students_list))