import math
1. 声明一个电脑类: 属性:品牌、颜色、内存, 方法:打游戏、写代码、看视频
a. 创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b. 通过attr相关方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play_game(self):
return "PUBG"
def code(self):
return 'hello world'
def wacth_videos(self):
return 'Game of Thrones'
comp1 = Computer("荣耀10", "铃兰白", "64G")
#查
print("型号", comp1.brand)
print("型号", getattr(comp1, 'brand'))
#改
comp1.color = ("魅力蓝")
setattr(comp1, "memory", "128G")
print("颜色", comp1.color)
print("内存", comp1.memory)
#添加
comp1.star = ("胡歌")
setattr(comp1, "company", "Huawei")
print("代言人", comp1.star)
print("制造商", comp1.company)
#删除
del comp1.memory
delattr(comp1, "company")
2. 声明一个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的方法:叫唤
人的属性:名字、年年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
print()
class Dog:
def __init__(self, dog_name='', color='', age=''):
self.dog_name = dog_name
self.color = color
self.age = age
def sing(self):
print("汪!汪!汪!")
class Person:
def __init__(self, name='', age='', dog=''):
self.name = name
self.age = age
self.dog = dog
def walk_with_dog(self, dog_name):
print(self.name+"带着"+dog_name+"出去溜达了")
dog1 = Dog("大黄", "gray", '2')
p1 = Person("小明", "22", dog1)
p1.walk_with_dog(dog1.dog_name)
3. 声明一个圆类,自己确定有哪些属性和方法
print()
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return math.pi*self.r**2
def perimeter(self):
return 2*math.pi*self.r
c1 = Circle(4)
print("面积是:", c1.area())
print("周长是:", c1.perimeter())
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
print()
class Students:
def __init__(self, name='', age='', stu_id=''):
self.name = name
self.age = age
self.stu_id = stu_id
def answer(self):
return "到"
def show_info(self):
return {"姓名":self.name, "年龄":self.age, "学号":self.stu_id}
stu1 = Students("阿建","22","022")
print(stu1.answer())
print(stu1.show_info())
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
print()
class ClassGrade:
def __init__(self, stus=[], class_name=''):
self.stus = stus
self.class_name = class_name
def add_stu(self, stu_name='', stu_age=0):
stu = {}
stu["姓名"]=stu_name
stu["年龄"]=stu_age
self.stus.append(stu)
return self.stus
def del_stu(self, stu_name):
for stu in self.stus:
if stu["姓名"]==stu_name:
self.stus.remove(stu)
break
#
def check_name(self, stu_name):
return stu_name+'到'
def aver_age(self):
sum_age = 0
for stu in self.stus:
sum_age += stu["年龄"]
return sum_age/len(self.stus)
def show_info(self):
return self.class_name, self.stus
class1 = ClassGrade(class_name="python1901")
#添加学生
class1.add_stu("阿毛", 22)
class1.add_stu("阿建", 23)
print(class1.show_info())
#删除学生
class1.del_stu("阿建")
print("删除学生后的班级信息:", class1.show_info())
#点名
print(class1.check_name("阿毛"))
#求学生平均年龄
print("该班学生的平均年龄是", class1.aver_age())
网友评论