1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Pc:
def __init__(self, brand='apple', color='black', ram='4g'):
self.brand = brand
self.color = color
self.ram = ram
def play_game(self):
return '打游戏'
def coding(self):
return '写代码'
def watch_video(self):
return '看视频'
# a
pc1 = Pc('MicroSoft', 'Silver', '8G')
# 查
pc1.brand
# 改
pc1.brand = 'Apple'
# 增
pc1.os = 'win10'
# 删
del pc1.os
# b
# 查
getattr(pc1, 'brand')
# 改
setattr(pc1, 'brand', 'Apple')
# 增
setattr(pc1, 'os', 'win10')
# 删
delattr(pc1, 'os')
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Pet:
def __init__(self, pet_name='dog', color='yellow', age='2'):
self.pet_name = pet_name
self.color = color
self.age = age
def bark(self):
print('%s开始了叫唤' % self.pet_name)
class Owner:
def __init__(self, name='jack', age=18, pet=None):
self.name = name
self.age = age
self.pet = pet
def walk_the_dog(self):
if not self.pet:
print('你没有狗!遛自己!!')
else:
print('%s牵着%s在散步' % (self.name, self.pet.pet_name))
d1 = Pet('大黄', '黄', '2')
p1 = Owner('小明', 18, d1)
p1.walk_the_dog()
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
pie = 3.1415926535897
def __init__(self, radius=1):
self.radius = radius
def square(self):
return Circle.pie * (self.radius ** 2)
def perimeter(self):
return Circle.pie * self.radius * 2
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student:
def __init__(self, name, age, stu_id):
self.name = name
self.age = age
self.stu_id = stu_id
def response(self):
print('%s,到!' % self.name)
def show_stu_info(self):
print('姓名:%s,年龄:%d,学号:%s' % (self.name, self.age, self.stu_id))
class Class:
def __init__(self, class_name):
self.class_name = class_name
self.students = []
def func1():
num = 1
while True:
yield 'stu'+str(num)
num += 1
self.create_id = func1()
def add_student(self):
name = input('学生姓名:')
age = int(input('学生年龄:'))
stu_id = next(self.create_id)
stu = Student(name, age, stu_id)
self.students.append(stu)
def del_student(self):
del_name = input('请输入要删除的学生的姓名:')
flag = False
for stu in self.students[:]:
if stu.name == del_name:
flag = True
stu.show()
value = input('是否删除(y/n):')
if value == 'y':
self.students.remove(stu)
if not flag:
print('没有该学生!')
def call_name(self):
pass
def show_all_students(self):
print('===========%s===========' % self.class_name)
for stu in self.students:
stu.show_stu_info()