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):
print('%s可以打游戏' % self.brand)
def write_code(self):
print('%s可以愉快的敲代码' % self.brand)
def watch_video(self):
print('%s可以快乐的看视频' % self.brand)
computer1 = Computer('戴尔', '蓝色', '8')
# 获取
print(computer1.brand) # 戴尔
# 修改
computer1.brand = '华硕'
print(computer1.brand) # 华硕
# 增加
computer1.read = '坏蛋是怎样炼成的'
print(computer1.read) # 坏蛋是怎样炼成的
# 删除
del computer1.color
print(computer1.color) # AttributeError: 'Computer' object has no attribute 'color'
# attr方法
computer2 = Computer('联想', '红色', 16)
# 获取
print(getattr(computer2, 'memory')) # 16
# 修改
setattr(computer2, 'read', '魔道祖师')
print(computer2.read) # 魔道祖师
# 增加
setattr(computer2, 'hard_disk', '1T')
print(computer2.hard_disk) # 1T
# 删除
delattr(computer2, 'memory')
print(computer2.memory) # AttributeError: 'Computer' object has no attribute 'memory'
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象:小明,让他拥有一条狗:大黄,然后让小明去遛大黄
class Dog:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def bark(self):
print('听,%s在汪汪叫' % self.name)
class Person:
def __init__(self, name, age, dog:Dog=None):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
if self.dog:
print('%s上街溜%s' % (self.name, self.dog.name))
else:
print('没有狗,溜自己!')
p1 = Person('小明', 18)
p1.dog = Dog('大黄', '黄色', 3)
p1.walk_the_dog()
3.声明一个圆类:
class P_valueerror(Exception):
def __str__(self):
return '当前属性不能赋值'
class Circle:
pi = 3.14
def __init__(self, radius, x=0, y=0):
self.radius = radius
self.x = x
self.y = y
self._area = 0
self._perimeter = 0
@property
def area(self):
return Circle.pi * self.radius ** 2
@area.setter
def area(self, value):
raise P_valueerror() # 用另一类创建对象
def perimeter(self):
return '圆的周长为%.2f' % (Circle.pi * self.radius * 2)
c1 = Circle(3)
print(c1.area)
# c1.area = 6
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
#创建一个学生类
def __init__(self, name, age, id1):
self.name = name
self.age = age
self.id1 = id1
def answer_to(self, *args):
if args:
print('%s到' % self.name)
else:
print('%s没到' % self.name)
def show_student_info(self):
print(self)
def __repr__(self):
return str(self.__dict__)[1:-1]
class Class:
def __init__(self, name):
self.students = []
self.name = name
def add_student(self, student):
self.students.append(student.__dict__)
def del_student(self, student):
stu1 = student.__dict__['id1']
count = 0
for dict1 in self.students[:]:
if stu1 == dict1['id1']:
self.students.remove(dict1)
print(self.students)
count += 1
if count == 0:
print('没有该学生')
def call_names(self, student):
pass
def students_average_scores(self):
sum1 = 0
for dict1 in self.students:
sum1 += dict1['age']
print('班级的平均年龄为%.f' % (sum1/len(self.students)))
class Student:
def __init__(self, name='', age=0, study_id=''):
self.name = name
self.age = age
self.study_id = study_id
def replied(self):
print('%s,到!' % self.name)
def show_info(self):
print('学号:%s 姓名:%s 年龄:%d' % (self.study_id, self.name, self.age))
def add_to_file(self):
"""将对象保存到本地"""
file_name = self.__class__.__name__+'.json'
with open('files/'+file_name, 'w', encoding='utf-8') as f:
json.dump(self.__dict__, f)
@classmethod
def get_student_in_file(cls):
"""将字典读出来抓换成对象"""
file_name = cls.__name__+'.json'
with open('files/'+file_name, encoding='utf-8') as f:
dict1 = json.load(f)
# 将字典转换成对象
stu = cls()
for key in dict1:
setattr(stu, key, dict1[key])
return stu
print('/=====验证=====')
stu1 = Student('小明', 18, '001')
stu1.add_to_file()
stu2 = Student.get_student_in_file()
print(stu2, stu2.name, stu2.age, stu2.study_id)
print('=====验证=====/')
class Class:
def __init__(self, name, students: list = []):
self.name = name
self.students = students
# 学号生成器
self.__id_generation = ('stu'+str(num).rjust(3, '0') for num in range(100))
def add_student(self):
"""添加学生"""
# 1.输入信息
name = input('姓名:')
age = int(input('年龄:'))
# 2.生成学号
study_id = next(self.__id_generation)
# 3.创建学生对象
stu = Student(name, age)
stu.study_id = study_id
# 4.保存到班级中
self.students.append(stu)
def del_student_with_name(self, name):
"""按姓名删除学生"""
count = 0
for stu in self.students[:]:
if stu.name == name:
count += 1
stu.show_info()
value = input('是否删除(Y/N):')
if value == 'Y' or value == 'y':
self.students.remove(stu)
if count == 0:
print('没有该学生!s')
def call_the_roll(self):
"""点名"""
for stu in self.students:
print(stu.name)
stu.replied()
def get_mean_age(self):
"""求平均年龄"""
sum1 = 0
for stu in self.students:
sum1 += stu.age
return sum1/len(self.students)
网友评论