1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,brand1,color1,ram1):
self.brand = brand1
self.color = color1
self.ram = ram1
def play_game(self,game):
return '游戏名是:', game
def write_code(self):
return '正在写代码'
def seevideo(self,):
print('再看视屏')
print('=======通过对象点的⽅方式获取、修改、添加和删除它的属性======')
# 创建
computer1 = Computer('华硕','蓝色','8G')
# 获取
print(computer1.brand,computer1.color,computer1.ram)
# 修改
computer1.ram ='4G'
print(computer1.ram)
# 添加
computer1.price = '8000'
print(computer1.price)
# 删除
del computer1.color
print(computer1.brand,computer1.ram)
print('========通过attr相关⽅方法去获取、修改、添加和删除它的属性========')
# 创建
c1= Computer('华硕','蓝色','8G')
# 获取
a1 = getattr(c1,'brand','没有品牌记录')
print(a1)
# 修改
b1 = setattr(c1,'color','红色')
print(getattr(b1,'color','颜色'))
# 添加
c1= setattr(c1,'price',10000)
print(getattr(c1,'price','价格'))
# 删)
d1 = delattr(c1,'brand')
print(getattr(c1,'brand','品牌'))
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
def __init__(self,name1,age1,dog1):
self.name = name1
self.age = age1
self.dog = dog1
def play_dog(self,dog):
return self.name +'在遛一只叫'+ dog +'的狗'
class Dog:
def __init__(self,dog_name,color1,dog_age):
self.name1= dog_name
self.color = color1
self.age = dog_age
def cry_out(self):
print('叫唤')
p1 = Person('小明',18,'二哈')
p1.play_dog('大黄')
print(p1.play_dog('大黄'))
3.声明⼀一个圆类,自己确定有哪些属性和方法
import math
class Circle:
def __init__(self,r,d):
self.r = r
self.d = d
def acreage(self,r):
return math.pi*r**2
def perimeter(self,r):
return math.pi*r*2
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student:
def __init__(self,name1,age1,id1):
self.name = name1
self.age = age1
self.id = id1
def answer(self):
return self.name + '到'
class Class:
def __init__(self,student,class_name):
self.student = []
self.class_name = class_name
#添加学⽣生
def add_student(self,stu):
self.student.append(stu)
# 删除学生
def del_student(self,name):
for index in range(len(self.student)):
if self.student[index] == name:
return self.student.pop(index)
# 点名
def answer(self,name):
for index in range(len(self.student)):
if self.student[index] == name:
return '到'
# 求班上学生的平均年龄
def avg(self,age):
count = 0
for students in self.student:
count += students.age
return count / len(self.student)