day15-作业
2019-01-12 本文已影响0人
馒头不要面
- 声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, color="黑色", flash="8G"):
self.brand = brand
self.color = color
self.flash = flash
def play_game(self):
print("打游戏中~")
def coding(self):
print("写代码中~")
def watch_video(self):
print("看视频中~")
# a. 创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
# 查
computer = Computer("联想")
print(computer.color)
# 改
computer.flash = "18G"
print(computer.flash)
# 增
computer.cpu = "i5"
print(computer.cpu)
# 删
del computer.cpu
# b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
# 查
print(getattr(computer, "color"))
# 改
setattr(computer, "flash", "8G")
print(computer.flash)
# 增
setattr(computer,"cpu","i7")
print(computer.cpu)
# 删
delattr(computer,"cpu")
print(getattr(computer,"cpu",None))
- 声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有⼀条狗大⻩,然后让⼩明去遛大黄
class Dog:
def __init__(self, name: str, color: str, age: int):
self.name = name
self.color = color
self.age = age
def call(self):
print(self.name + "在叫唤")
class Person:
def __init__(self, name: str, age: int, dog: Dog):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
print(self.name, "正在遛他的", self.dog.name)
self.dog.call()
dh = Dog("大黄", "黄色", 2)
xm = Person("小明", 12, dh)
xm.walk_the_dog()
- 声明一个圆类:
class Circle:
PI = 3.1415926
def __init__(self, radius):
self.radius = radius
def area(self):
return self.radius ** 2 * self.PI
def perimeter(self):
return 2 * self.PI * self.radius
c = Circle(3)
print(c.area())
print(c.perimeter())
- 创建一个学生类: 属性:姓名,年龄,学号 方法:答到,展示学生信息
创建一个班级类: 属性:学生,班级名 方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
def __init__(self, name: str, age: int, id: str):
self.name = name
self.age = age
self.id = id
def __repr__(self):
return ("学号:%s 姓名:%s 年龄:%d" % (self.id, self.name, self.age))
class Class:
def __init__(self, class_name: str):
self.all_student = []
self.class_name = class_name
def add_student(self, student: Student):
self.all_student.append(student)
def del_student(self, student):
for s in self.all_student[:]:
if s == student:
self.all_student.remove(s)
def average(self):
age_sum = sum(x.age for x in self.all_student)
return age_sum / len(self.all_student)
def __repr__(self):
s = ""
for student in self.all_student:
s += str(student) + "\n"
return s
classa = Class("三年级二班")
classa.add_student(Student("小明", 10, "001"))
classa.add_student(Student("小东", 12, "002"))
classa.add_student(Student("小强", 13, "003"))
classa.add_student(Student("小红", 14, "004"))
print(classa.average())
print(classa)