1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,brand,memory,color):
self.brand = brand
self.memory = memory
self.color = color
def play_game(self):
print("打游戏")
def code(self):
print("写代码")
def browse_video(self):
print("看视频")
#a.
computer1 = Computer('DELL', '8G', '蓝色')
print(computer1.color)
computer1.brand = '16G'
computer1.size = '15寸'
print(computer1.__dict__)
#b
color1 = getattr(computer1,'color')
print(color1)
setattr(computer1,'color','红色')
print(computer1.color)
setattr(computer1,'144HZ屏', '是')
print(computer1.__dict__)
delattr(computer1,'144HZ屏')
print(computer1.__dict__)
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
def __init__(self, name, age, dog=None):
self.name = name
self.age = age
self.dog = dog
def wolk_dog(self, other):
print("%s在遛%s." % (self.name, self.dog))
class Dog:
def __init__(self,name,color,age):
self.name = '大黄'
self.color = '黄色'
def bark(self):
print('汪汪!')
person1 = Person('小明', 23)
dog1 = Dog('大黄', '黄色', 5)
person1.wolk_dog(dog1)
dog1.brak()
3.声明⼀一个圆类:
class Circle:
def __init__(self, x, y, r):
self.x = x
self.y = y
self.r = r
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学生,班级名
方法:添加学⽣,删除学生,点名, 求班上学生的平均年龄
class Student(object):
def __init__(self, name, age=0, study_id=''):
self.name = name
self.age = age
self.study_id = study_id
def reply(self):
print("s%, 到!" % self.name)
def show_info(self):
print("名字:%s, 年龄:%d, 学号:%s" % (self.name, self.age, self.study_id))
class Class(object):
def __init__(self, name:str)
self.name = name
self.students = []
self.__creat_id = (self.name+str(x).rjust(3, '0') for x in range(1,101))
def add_student(self):
# 输入信息
name = input("姓名:")
age = int(input("年龄:"))
study_id = next(self.__creat_id)
stu1 = Student(name, age, study_id)
self.students.append(stu1)