1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,make,color,save):
self.make = make
self.color = color
self.save = save
def play_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def look_video(self):
print('看视频')
computer1 = Computer('联想','black','32g')
computer1.color = 'white'
computer1.make = '戴尔'
print(getattr(computer1,'make'))
setattr(computer1,'color','red')
delattr(computer1,'save')
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
def __init__(self,name,age,dog):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
print('{}在遛{}'.format(self.name,self.dog.name))
class Dog:
def __init__(self,name,color,age):
self.name = name
self.color = color
self.age = age
def call_dog(self):
print('{}在叫'.format(self.name))
dog = Dog('大黄','yellow',3)
person = Person('小明',18,dog)
person.walk_dog()
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
def __init__(self,width,height):
self.width = width
self.height = height
def count_area(self):
self.area = self.width * self.height
return self.area
def count_permeter(self):
self.permeter = (self.width + self.height) * 2
return self.permeter
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Classmate:
def __init__(self,class_name):
self.class_name = class_name
self.students = []
def append_student(self,student):
self.students.append(student)
def append_student(self,student):
self.students.remove(student)
def call_name(self):
for student in self.students:
student.speak()
def avg_age(self):
sum = 0
for student in self.students:
sum += student.age
return '学生的平均年龄是{}'.format(sum/len(self.students))
class Student:
def __init__(self,name,age,student_id):
self.name = name
self.age = age
self.student_id = student_id
def speak(self):
print('{}到'.format(self.name))
def print_information(self):
print(self.name,self.age,self.student_id)