• Python面向对象与pickle对象持久化示例


    1. import pickle, os
    2. class AddressBook(object):
    3. def __init__(self, name = None, address = None, email = None, phone = None):
    4. self.name = name
    5. self.address = address
    6. self.email = email
    7. self.phone = phone
    8. self.contacts = {}
    9. self.filename = 'addressbook'
    10. def __str__(self):
    11. return '[Name: {0} | Address: {1} | Email: {2} | Phone: {3}]'.format(self.name, self.address, self.email, self.phone)
    12. def __repr__(self):
    13. return '[Name: {0} | Address: {1} | Email: {2} | Phone: {3}]'.format(self.name, self.address, self.email, self.phone)
    14. # 追加通讯信息到地址簿
    15. def addContacts(self):
    16. try:
    17. if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0:
    18. myAddressBook = open(self.filename, 'rb')
    19. data = pickle.load(myAddressBook)
    20. myAddressBook.close()
    21. else:
    22. myAddressBook = open(self.filename, 'wb')
    23. data = {}
    24. contact = self.getDetailsFromUser()
    25. data[contact['Name']] = contact
    26. myAddressBook = open(self.filename, 'wb')
    27. # 持久化对象
    28. pickle.dump(data, myAddressBook)
    29. myAddressBook.close()
    30. print(data)
    31. print('Contact Added Successfully!')
    32. except:
    33. print('There was an error! Contact was not added.')
    34. finally:
    35. myAddressBook.close()
    36. # 初始化地址簿各元素的输入
    37. def getDetailsFromUser(self):
    38. try:
    39. self.contacts['Name'] = str(input('Enter Contact\'s Full Name: '))
    40. self.contacts['Address'] = str(input('Enter Contact\'s Address: '))
    41. self.contacts['Email'] = str(input('Enter Contact\'s Email Address: '))
    42. self.contacts['Phone'] = int(input('Enter Contact\'s Phone Number: '))
    43. return self.contacts
    44. except KeyboardInterrupt as error:
    45. raise error
    46. # 显示地址簿里的所有地址信息
    47. def displayContacts(self):
    48. if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0:
    49. myAddressBook = open(self.filename, 'rb')
    50. data = pickle.load(myAddressBook)
    51. myAddressBook.close()
    52. if data:
    53. for records in data.values():
    54. print(records)
    55. myAddressBook.close()
    56. else:
    57. print('No Record in database.')
    58. # 按照姓名搜索地址薄,返回地址薄对象信息
    59. def searchContacts(self):
    60. if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0:
    61. myAddressBook = open(self.filename, 'rb')
    62. data = pickle.load(myAddressBook)
    63. myAddressBook.close()
    64. try:
    65. contactToSearch = input('Enter the name of the contact to search: ')
    66. counter = 0
    67. for contact in data.values():
    68. if contactToSearch in contact['Name']:
    69. print(data[contact['Name']])
    70. counter += 1
    71. if counter == 0:
    72. print('No record found whose name is:', contactToSearch)
    73. except:
    74. print('Error occured!')
    75. else:
    76. print('No Record in database.')
    77. # 修改通讯薄信息,支持按照姓名、地址、邮箱、电话等信息更新
    78. def modifyContacts(self):
    79. if os.path.exists(self.filename) and os.path.getsize(self.filename) > 0:
    80. myAddressBook = open(self.filename, 'rb')
    81. data = pickle.load(myAddressBook)
    82. myAddressBook.close()
    83. try:
    84. contactToModify = input('Enter the name of the contact to modify (Only enter full name): ')
    85. # Search for the record to update
    86. for contact in data.values():
    87. if contactToModify == contact['Name']:
    88. contact = data[contactToModify]
    89. break
    90. option = int(input('1. To modify name, 2. To modify address, 3. To modify email, 4. To modify phone: '))
    91. if option == 1:
    92. contact['Name'] = input('Enter Name to modify: ')
    93. del data[contactToModify]
    94. data[contact['Name']] = contact
    95. print('Successful')
    96. elif option == 2:
    97. contact['Address'] = input('Enter Address to modify: ')
    98. del data[contactToModify]
    99. data[contactToModify] = contact
    100. print('Successful')
    101. elif option == 3:
    102. contact['Email'] = input('Enter Email to modify: ')
    103. del data[contactToModify]
    104. data[contactToModify] = contact
    105. print('Successful')
    106. elif option == 4:
    107. contact['Phone'] = input('Enter Phone to modify: ')
    108. del data[contactToModify]
    109. data[contactToModify] = contact
    110. print('Successful')
    111. else:
    112. print('Incorrect option selected.')
    113. except:
    114. print('Error occured. No such record found. Try Again!')
    115. finally:
    116. myAddressBook = open(self.filename, 'wb')
    117. pickle.dump(data, myAddressBook)
    118. myAddressBook.close()
    119. else:
    120. print('No Record in database.')
    121. if __name__ == '__main__':
    122. myBook = AddressBook()
    123. print('Enter 1. To Add Contacts 2. For Searching a Contact 3. For Modifying a Contact 4. To Display Contacts 5. To Exit')
    124. while True:
    125. choice = int(input('Enter your choice: '))
    126. #将用户操作需求与对应方法绑定
    127. if choice == 1:
    128. myBook.addContacts()
    129. elif choice == 2:
    130. myBook.searchContacts()
    131. elif choice == 3:
    132. myBook.modifyContacts()
    133. elif choice == 4:
    134. myBook.displayContacts()
    135. elif choice == 5:
    136. exit()
    137. else:
    138. print('Invalid Option. Try Again!')

  • 相关阅读:
    CS5266BN说明书|CS5266BN QFN48封装规格书|CS5266BN设计资料
    RAW-GNN: RAndom Walk Aggregation based Graph Neural Network
    go进行大文件的分块并发处理
    app如何新增广告位以提升广告变现收益?
    CentOS 7 下 MongoDB 日志切割
    Windows用VM虚拟机安装MacOS Ventura 13.6系统全流程教程(附资源)
    通义大模型使用指南之通义听悟
    Ubuntu 22.04.3 LTS中安装singularity
    uni-app自定义导航栏
    百分位(P95,P99)统计awk脚本
  • 原文地址:https://blog.csdn.net/shenliang1985/article/details/126033834