1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
__slots__ = ('brand', 'color', 'memory', 'price', 'cpu')
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play_game(self):
print('打游戏')
def write_code(self):
print('敲代码')
def watch(self):
print('看电视')
computer1 = Computer('dell', 'red', '16G')
computer2 = Computer('hp', 'black', '8G')
print(computer1.brand, computer1.color, computer1.memory)
print(computer2.brand, computer2.color, computer2.memory)
computer1.play_game()
computer2.write_code()
computer2.watch()
computer1.cpu = 'inter'
print(computer1.cpu)
setattr(computer1, 'price', 'rmb:8080')
print(computer1.price)
delattr(computer2, 'brand')
del computer2.color
print(computer2.brand, computer2.color, computer2.memory)
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的⽅方法:叫唤
人的属性:名字、年龄、狗
人的⽅法:遛狗
a.创建人的对象小明,让他拥有一条狗⼤黄,然后让小明去遛大黄
class Person:
__slots__ = ('name', 'age', 'dog')
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def hang_dog(self):
print('%s牵着%s去公园玩儿' % (self.name, self.dog))
class Dog:
__slots__ = ('dog_name', 'dog_color', 'dog_age')
def __init__(self, dog_name, dog_color, dog_age):
self.dog_name = dog_name
self.dog_color = dog_color
self.dog_age = dog_age
def bark(self):
print('%s在公园汪汪叫' % self.dog_name)
p1 = Person('小明', 16, '大黄')
dog1 = Dog(p1.dog, 'white', '2')
print(p1.name, p1.age, p1.dog)
print(dog1.dog_name, dog1.dog_color, dog1.dog_age)
p1.hang_dog()
dog1.bark()
3.声明⼀一个圆类,自己确定有哪些属性和方法
from math import pi
class Circle:
__slots__ = ('r', 'color')
def __init__(self, r, color):
self.r = r
self.color = color
def premiter(self):
print(2*pi*self.r)
def area(self):
print(pi*self.r*self.r)
circle1 = Circle(5, 'red')
circle1.area()
circle1.premiter()
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建一个班级类:
属性:学生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student:
__slots__ = ('name', 'age', 'stu_id', 'class_id')
def __init__(self, name, age, stu_id):
self.name = name
self.age = age
self.stu_id = stu_id
def reply(self):
print('%s已就位' % self.name)
stu1 = Student('王力', '18', '1904')
stu1.reply()
class Class:
__slots__ = ('name', 'class_id', 'age', 'stu_id')
def __init__(self, name, class_id, age, stu_id):
self.name = name
self.class_id = class_id
self.age = age
self.stu_id = stu_id
def add_stu(self):
self.name = input('学生姓名:')
self.age = input('学生年龄:')
self.stu_id = input('学生学号:')
self.class_id = input('学生班级:')
def del_stu(self):
self.name = input('要删除的学生姓名:')
del (self.name, self.age, self.stu_id, self.class_id)
print('删除成功')
class1 = Class(None, None, None, None)
class1.add_stu()
print(class1.name, class1.age, class1.stu_id, class1.class_id)
class1.del_stu()
print(class1.name, class1.age, class1.stu_id, class1.class_id)