Chinaunix首页 | 论坛 | 博客
  • 博客访问: 423643
  • 博文数量: 117
  • 博客积分: 5235
  • 博客等级: 大校
  • 技术积分: 1775
  • 用 户 组: 普通用户
  • 注册时间: 2007-09-12 15:51
文章分类

全部博文(117)

文章存档

2012年(9)

2011年(2)

2010年(21)

2009年(13)

2008年(72)

我的朋友

分类: Python/Ruby

2012-03-14 16:17:45

 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) |
给主人留下些什么吧!~~