20. IO
20.1 file
f = file(fname, "w") //w,a,r
20.2 object
import cPickle as p
list = [1,2]
f = file(fname, "w")
p.dump(list, f)
f.close()
del list
f = file(fname)
list2 = p.load(f)
f.close()
print list2
20.3 key
raw_input("Please type a number:") //get a number from keyboard
21. Exception
21.1 try ... except ...
try:
...
except (EOFError, OtherException):
...
except:
...
21.2 raise
22. variable parameters
def max(first, *others) //others is a list
def min(first, **others) //others is a dictionary
23. others
23.1 exec and eval
exec 'print "hello world"'
eval('3+4')
23.2 lambda //define a simple anonymous function
plus = lambda x: x+2
print plus(4) //output 6
----------------------------------
class ShortInputException(Exception): //define a exception class
'''A user-defined exception class.'''
def __init__(self, length, atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something --> ')
if len(s) < 3:
raise ShortInputException(len(s), 3)
# Other work can continue as usual here
except EOFError:
print '\nWhy did you do an EOF on me?'
except ShortInputException, x:
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length, x.atleast)
else:
print 'No exception was raised.'
----------------------------------
阅读(344) | 评论(0) | 转发(0) |