Python如何实现JavaBeans
本文小编为大家详细介绍“Python如何实现JavaBeans”,内容详细,步骤清晰,细节处理妥当,希望这篇“Python如何实现JavaBeans”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。
在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.pyclass 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.pyclass 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 Schoolfrom Student import Studentstudent_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
千年虫
读到这里,这篇“Python如何实现JavaBeans”文章已经介绍完毕,想要掌握这篇文章的知识点还需要大家自己动手实践使用过才能领会,如果想了解更多相关内容的文章,欢迎关注编程网行业资讯频道。
免责声明:
① 本站未注明“稿件来源”的信息均来自网络整理。其文字、图片和音视频稿件的所属权归原作者所有。本站收集整理出于非商业性的教育和科研之目的,并不意味着本站赞同其观点或证实其内容的真实性。仅作为临时的测试数据,供内部测试之用。本站并未授权任何人以任何方式主动获取本站任何信息。
② 本站未注明“稿件来源”的临时测试数据将在测试完成后最终做删除处理。有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341