在JavaBeans中有这样的一个描述:当一些信息需要使用类似于字典嵌套字典再嵌套列表这种很深的结构来储存的时候,请改用类来储存。实际上,这样的思想也可以用于Python中。
网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、小程序制作、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了乐都免费建站欢迎大家使用!场景:在Python中,以前可能会这样写嵌套字典结构
school_list = [{'school_name': 'SZ',
'class_id': '001',
'stu_num': 45,
'student':{'stu_id': '001',
'stu_name': 'xiaohong',
'stu_score': 90
}
},
{'school_name': 'Fxxking U',
'class_id': '002',
'stu_num': 40,
'student':{'stu_id': '002',
'stu_name': 'xiaobai',
'stu_score': 98
}
}]
而当我们要访问比较深层结构中的数据时可能要这样:
print(school_list[0]['student']['stu_id'])
这样在取用时未免太麻烦,而且一旦嵌套结构越深层,取用时就越麻烦。
JavaBeans in Python如果借鉴JavaBeans的思维,将此用类实现,会是以下这样:
# School.py
class School(object):
def __init__(self,school_name='',class_id='',stu_num=0,student=None) ->None:
self._school_name = school_name
self._class_id = class_id
self._stu_num = stu_num
self._student = student
@property
def school_name(self):
return self._school_name
@school_name.setter
def school_name(self,new_name):
self._school_name = new_name
@property
def class_id(self):
return self._class_id
@class_id.setter
def class_id(self,new_id):
self._class_id = new_id
@property
def stu_num(self):
return self._stu_num
@stu_num.setter
def stu_num(self,new_num):
self._stu_num = new_num
@property
def student(self):
return self._student
@student.setter
def student(self,new_student):
self._student = new_student
# Student.py
class Student(object):
def __init__(self,stu_id='',stu_name='',stu_score=0) ->None:
self._stu_id = stu_id
self._stu_name = stu_name
self._stu_score = stu_score
@property
def stu_id(self):
return self._stu_id
@stu_id.setter
def stu_id(self,new_id):
self._stu_id = new_id
@property
def stu_name(self):
return self._stu_name
@stu_name.setter
def stu_name(self,new_name):
self._stu_name = new_name
@property
def stu_score(self):
return self._stu_score
@stu_score.setter
def stu_score(self,new_score):
self._stu_score = new_score
我们将原有的嵌套字典数据转换为两个类实现,且分别在School.py与Student.py两个文件中,在类中我们对原本的数据以装饰器粉饰为属性从而使其可以进行读取与修改。这样一来,我们就可以用类属性的方式去访问我们想要的数据。
程序代码:
from School import School
from Student import Student
student_007 = Student(stu_id='007',stu_name='零零漆',stu_score=99)
school_Princeton = School(school_name='Princeton U',class_id='005',stu_num=1000,student=student_007)
student_qnc = Student(stu_id='250',stu_name='千年虫',stu_score=60)
school_Fuxxking = School(school_name='Fuxxking U',class_id='009',stu_num=500,student=student_qnc)
school_list = [school_Princeton,school_Fuxxking]
for i in school_list:
print(i.school_name)
print(i.class_id)
print(i.stu_num)
stu = i.student
print(stu.stu_name)
输出结果:
Princeton U
005
1000
零零漆
Fuxxking U
009
500
千年虫
总结:将深层次的嵌套结果转换为用类实现的好处是,在初始化类对象后,可以直接使用
实例.属性
的方式访问想要的数据,且关键数据在类中定义的很详细。
你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧