This example is a basic example of Python. It involves Python basics, including syntax, dictionary-type data structures, classes, import-to-database, pickle-implemented memory, and exception handling.
The example is a phone book. You can add, delete, modify, retrieve a list, or obtain a single user's phone book.
In Python, both Pickle and cPickle can complete memory tasks. However, cPickle is written in C language and is said to have a performance higher than pickle1000x.
Pickle in Python stores an object into a file. As a fully object-oriented language, Python instantiates a dictionary object when declaring/initializing a variable, such as a dictionary, or an associated array. Then, Pickle can store the dictionary object into a file. When reading the dictionary, not only the dictionary is complete, but also the dictionary object method can be used.
Python uses indentation to separate statement blocks. Because I copied it in VIM, the indentation may be problematic in my blog.
# Introduce the pickle Library. CPickle is 1000 times faster than Pickle
Import cPickle as pickle
# Import Pickle as pickle
# Phone book
Class Address:
# Initialization
Def _ init _ (self ):
# Store data in that file
Self. filename = 'list. Data'
F = file (self. filename)
# If the file is new or empty, it is initialized to an empty Dictionary (associated array)
Try:
Self. lists = pickle. load (f)
Except t:
Print 'address Book is empty. initializing .....'
Self. lists = {}
F. close ()
# Add a contact
Def add (self, name, age, mobile, mail ):
NewUser = {'name': name, 'age': age, 'mobile': mobile, 'mail': mail}
Self. lists [name] = newUser
# Deleting a contact
Def delete (self, name ):
If name in self. lists:
Del self. lists [name]
Print 'delete', name
Else:
Print 'no exists', name
# Getting a list
Def getList (self ):
Print 'address Book List :'
Print self. lists
# Obtain the contact with the specified name
Def getOne (self, name ):
If name in self. lists:
Print self. lists [name]
Else:
Print 'not Exists: ', name
# Modify a contact
Def edit (self, name, key, value ):
Self. lists [name] [key] = value
# When the class stops running, execute the special method _ del __, that is, the destructor.
Def _ del _ (self ):
F = file (self. filename, 'w ')
Pickle. dump (self. lists, f)
F. close ()
# Initialize the phone book Class
Obj = Address ()
# Add a contact
Obj. add ('Lane ', 23,185 00000000, 'lixuan868686 @ 163.com ')
# Retrieve the list of all contacts
Obj. getList ()
# Obtain the contact information of lane.
Obj. getOne ('Lane ')
# Obtain the contact information of xiaoming.
Obj. getOne ('xiaoming ')
// Modify lane's age to 24.
Obj. edit ('Lane ', 'age', '24 ')