- 声明一个电脑类
属性:品牌、颜色、内存大小
方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性
class Pc:
def __init__(self,brand,color,storage):
self.brand = brand
self.color = color
self.storage = storage
def play_game(self):
print('玩游戏')
def type_code(self):
print('敲代码')
def watch_video(self):
print('看视频')
pc1 = Pc('asus','silver','64')
print(pc1.brand)
pc1.price = '998'
print(pc1.price)
pc1.brand = 'lenovo'
print(pc1.brand)
del pc1.color
# print(pc1.color)
print(getattr(pc1,'storage'))
setattr(pc1,'market_time',2018)
print(pc1.market_time)
setattr(pc1,'price',4399)
print(pc1.price)
delattr(pc1,'brand')
# print(pc1.brand)
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的 法:叫唤
人的属性:名字、 年龄、狗
人的方法:遛狗
a.创建人的对象名字叫小明,让他拥有一条狗 ,然后让小明去遛狗
class Dog:
def __init__(self,d_name,d_color,d_age):
self.name = d_name
self.color = d_color
self.age = d_age
def bark(self):
print('汪汪汪')
class Person:
def __init__(self,p_name,p_age):
self.name = p_name
self.age = p_age
self.dog = getattr(dog1,'name')
def walk_dog(self):
print('%s正在遛%s'% (self.name,self.dog))
dog1 = Dog('大黄','黑色',1)
print(dog1.name)
print(dog1.color)
print(dog1.age)
person1 = Person('小明',18)
person1.walk_dog()
3.声明一个矩形类:
属性: 长、宽
方法:计算周长和面积
a.创建不同的矩形,并且打印其周长和面积
class Rectangle:
def __init__(self,length,width):
self.length = length
self.width = width
def circu(self):
circu = (self.length+self.width)*2
print(circu)
def area(self):
area = self.length * self.width
print(area)
rec1 = Rectangle(60,5)
rec1.circu()
rec1.area()
4.创建一个学生类: ()
属性:姓名,年龄,学号,成绩
方法:答到,展示学生信息
创建一个班级类: 属性:学生,班级名
方法:添加学生,删除学生,点名, 获取班级中所有学生的平均值, 获取班级中成绩最好的学生
def __init__(self,name,age,stu_num,scores):
self.name = name
self.age = age
self.stu_num = stu_num
self.scores = scores
def sign_in(self):
print("%s已到"% self.name)
def show_stu(self):
print(self.name,self.age,self.stu_num,self.scores)
class Class:
def __init__(self,class_num,class_stu):
# pass
# self.class_num = class_num
# self.class_stu = class_stu
def add_stu(self):
global class_stu
self.stu = getattr(stu1,'name')
self.age = getattr(stu1,'age')
self.stu_num = getattr(stu1,'stu_num')
self.scores = getattr(stu1,'scores')
# new_dict = {'name':stu,}
new_dict = {'name':self.stu,'age':self.age,'stu_num':self.stu_num,'scores':self.scores}
class_stu.append(new_dict)
print(class_stu)
# def del_stu(self):
# global class_stu
# name = input('请输入要删除学生姓名:')
# for x in class_stu:
# if name == class_stu[x]['name']:
# delattr(class_stu[x])
stu1 = Students('hqf',18,666,100)
stu1.show_stu()
# class1 = Class('py1807','stu1')
# class1 = Class
class1 = Class('stu1')
class1.add_stu(stu1)