分享

Python 基础语法(四)

韩克拉玛寒 发表于 2015-3-17 22:21:31 [显示全部楼层] 回帖奖励 阅读模式 关闭右栏 4 10922
本帖最后由 韩克拉玛寒 于 2015-3-17 13:55 编辑
问题导读:
1、深入理解Python标准库:sys模块、os模块都有哪些方法?
2、如何学习理解:特殊方法,综合列表,函数接收元组/列表/字典等知识点?





接上篇   Python 基础语法(一)
接上篇   Python 基础语法(二)
接上篇   Python 基础语法(三)


十、Python标准库
  Python标准库是随Pthon附带安装的,包含了大量极其有用的模块。

  1. sys模块  sys模块包含系统对应的功能
  • sys.argv  ---包含命令行参数,第一个参数是py的文件名
  • sys.platform  ---返回平台类型
  • sys.exit([status])  ---退出程序,可选的status(范围:0-127):0表示正常退出,其他表示不正常,可抛异常事件供捕获
  • sys.path    ---程序中导入模块对应的文件必须放在sys.path包含的目录中,使用sys.path.append添加自己的模块路径
  • sys.modules  ---This is a dictionary that maps module names to modules which have already been loaded
  • sys.stdin,sys.stdout,sys.stderr  ---包含与标准I/O 流对应的流对象
  1. s = sys.stdin.readline()
  2. sys.stdout.write(s)
复制代码


       2. os模块  该模块包含普遍的操作系统功能、
  • os.name字符串指示你正在使用的平台。比如对于Windows,它是'nt',而对于Linux/Unix用户,它是'posix'
  • os.getcwd()函数得到当前工作目录,即当前Python脚本工作的目录路径
  • os.getenv()和os.putenv()函数分别用来读取和设置环境变量
  • os.listdir()返回指定目录下的所有文件和目录名
  • os.remove()函数用来删除一个文件
  • os.system()函数用来运行shell命令
  • os.linesep字符串给出当前平台使用的行终止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'
  • os.sep 操作系统特定的路径分割符
  • os.path.split()函数返回一个路径的目录名和文件名
  • os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录
  • os.path.existe()函数用来检验给出的路径是否真地存在

十一、其他

  1. 一些特殊的方法

名称
说明
__init__(self,...)这个方法在新建对象恰好要被返回使用之前被调用。
__del__(self)恰好在对象要被删除之前调用。
__str__(self)在我们对对象使用print语句或是使用str()的时候调用。
__lt__(self,other)当使用 小于 运算符(<)的时候调用。类似地,对于所有的运算符(+,>等等)都有特殊的方法。
__getitem__(self,key)使用x[key]索引操作符的时候调用。
__len__(self)对序列对象使用内建的len()函数的时候调用。

       下面的类中定义了上表中的方法:
  1. class Array:
  2.     __list = []
  3.     def __init__(self):
  4.         print "constructor"
  5.     def __del__(self):
  6.         print "destructor"
  7.     def __str__(self):
  8.         return "this self-defined array class"
  9.     def __getitem__(self, key):
  10.         return self.__list[key]
  11.     def __len__(self):
  12.         return len(self.__list)
  13.     def Add(self, value):
  14.         self.__list.append(value)
  15.     def Remove(self, index):
  16.         del self.__list[index]
  17.     def DisplayItems(self):
  18.         print "show all items----"
  19.         for item in self.__list:
  20.             print item
  21. arr = Array()   #constructor
  22. print arr    #this self-defined array class
  23. print len(arr)   #0
  24. arr.Add(1)
  25. arr.Add(2)
  26. arr.Add(3)
  27. print len(arr)   #3
  28. print arr[0]   #1
  29. arr.DisplayItems()
  30. #show all items----
  31. #1
  32. #2
  33. #3
  34. arr.Remove(1)
  35. arr.DisplayItems()
  36. #show all items----
  37. #1
  38. #3
  39. #destructor
复制代码

  2. 综合列表
    通过列表综合,可以从一个已有的列表导出一个新的列表。
  1. list1 = [1, 2, 3, 4, 5]
  2. list2 = [i*2 for i in list1 if i > 3]
  3. print list1  #[1, 2, 3, 4, 5]
  4. print list2  #[8, 10]
复制代码

  3. 函数接收元组/列表/字典
    当函数接收元组或字典形式的参数的时候,有一种特殊的方法,使用*和**前缀。该方法在函数需要获取可变数量的参数的时候特别有用。
    由于在args变量前有*前缀,所有多余的函数参数都会作为一个元组存储在args中。如果使用的是**前缀,多余的参数则会被认为是一个字典
  的键/值对。
  1. def powersum(power, *args):
  2.     total = 0
  3.     for i in args:
  4.         total += pow(i, power)
  5.     return total
  6. print powersum(2, 1, 2, 3)   #14
复制代码
  1. def displaydic(**args):
  2.     for key,value in args.items():
  3.         print "key:%s;value:%s" % (key, value)
  4. displaydic(a="one", b="two", c="three")
  5. #key:a;value:one
  6. #key:c;value:three
  7. #key:b;value:two
复制代码


      4. lambda
    lambda语句被用来创建新的函数对象,并在运行时返回它们。lambda需要一个参数,后面仅跟单个表达式作为函数体,而表达式的值被这个
  新建的函数返回。 注意,即便是print语句也不能用在lambda形式中,只能使用表达式。
  1. func = lambda s: s * 3
  2. print func("peter ")  #peter peter peter
  3. func2 = lambda a, b: a * b
  4. print func2(2, 3)  #6
复制代码

  5. exec/eval
    exec语句用来执行储存在字符串或文件中的Python语句;eval语句用来计算存储在字符串中的有效Python表达式。
  1. cmd = "print 'hello world'"
  2. exec cmd   #hello world
  3. expression = "10 * 2 + 5"
  4. print eval(expression)    #25
复制代码

  6. assert
    assert语句用来断言某个条件是真的,并且在它非真的时候引发一个错误--AssertionError。
  1. flag = True
  2. assert flag == True
  3. try:
  4.     assert flag == False
  5. except AssertionError, err:
  6.     print "failed"
  7. else:
  8.     print "pass"
复制代码

  7. repr函数
    repr函数用来取得对象的规范字符串表示。反引号(也称转换符)可以完成相同的功能。
    注意,在大多数时候有eval(repr(object)) == object。
    可以通过定义类的__repr__方法来控制对象在被repr函数调用的时候返回的内容。
  1. arr = [1, 2, 3]
  2. print `arr`    #[1, 2, 3]
  3. print repr(arr)    #[1, 2, 3]
复制代码

十二、练习
    实现一个通讯录,主要功能:添加、删除、更新、查询、显示全部联系人
  1. import cPickle
  2.   import os
  3.   import sys
  4.   
  5.   class Contact:
  6.       def __init__(self, name, phone, mail):
  7.           self.name = name
  8.           self.phone = phone
  9.           self.mail = mail
  10.      def Update(self, name, phone, mail):
  11.          self.name = name
  12.          self.phone = phone
  13.          self.mail = mail
  14.      def display(self):
  15.          print "name:%s, phone:%s, mail:%s" % (self.name, self.phone, self.mail)
  16. # begin
  17. # file to store contact data
  18. data = os.getcwd() + os.sep + "contacts.data"
  19. while True:
  20.      print "-----------------------------------------------------------------------"
  21.      operation = raw_input("input your operation(add/delete/modify/search/all/exit):")
  22.      if operation == "exit":
  23.         sys.exit()
  24.      if os.path.exists(data):
  25.          if os.path.getsize(data) == 0:
  26.              contacts = {}
  27.          else:
  28.              f = file(data)
  29.              contacts = cPickle.load(f)
  30.              f.close()
  31.      else:
  32.          contacts = {}
  33.      if operation == "add":
  34.          flag = False
  35.          while True:
  36.              name = raw_input("input name(exit to back choose operation):")
  37.              if name == "exit":
  38.                  flag = True
  39.                  break
  40.              if name in contacts:
  41.                  print "the name already exists, please input another or input 'exit' to back choose operation"
  42.                  continue
  43.              else:
  44.                  phone = raw_input("input phone:")
  45.                  mail = raw_input("input mail:")
  46.                  c = Contact(name, phone, mail)
  47.                  contacts[name] = c
  48.                  f = file(data, "w")
  49.                  cPickle.dump(contacts, f)
  50.                  f.close()
  51.                  print "add successfully."
  52.                  break
  53.      elif operation == "delete":
  54.          name = raw_input("input the name that you want to delete:")
  55.          if name in contacts:
  56.              del contacts[name]
  57.              f = file(data, "w")
  58.              cPickle.dump(contacts, f)
  59.              f.close()
  60.              print "delete successfully."
  61.          else:
  62.              print "there is no person named %s" % name
  63.      elif operation == "modify":
  64.          while True:
  65.              name = raw_input("input the name which to update or exit to back choose operation:")
  66.              if name == "exit":
  67.                  break
  68.              if not name in contacts:
  69.                  print "there is no person named %s" % name
  70.                  continue
  71.              else:
  72.                  phone = raw_input("input phone:")
  73.                  mail = raw_input("input mail:")
  74.                  contacts[name].Update(name, phone, mail)
  75.                  f = file(data, "w")
  76.                  cPickle.dump(contacts, f)
  77.                  f.close()
  78.                  print "modify successfully."
  79.                  break
  80.      elif operation == "search":
  81.          name = raw_input("input the name which you want to search:")
  82.          if name in contacts:
  83.              contacts[name].display()
  84.          else:
  85.              print "there is no person named %s" % name
  86.      elif operation == "all":
  87.          for name, contact in contacts.items():
  88.              contact.display()
  89.      else:
  90.          print "unknown operation"
复制代码


-----------------------------------------------------   结束  -----------------------------------------------------





来自群组: about云小组群
欢迎加入about云群425860289432264021 ,云计算爱好者群,亦可关注about云腾讯认证空间||关注本站微信

已有(4)人评论

跳转到指定楼层
Libra0507 发表于 2015-4-13 14:40:21
回复

使用道具 举报

zhmg23 发表于 2015-7-19 10:12:15
写的非常不错!
回复

使用道具 举报

a530491093 发表于 2016-3-8 11:13:57
不错不错,学习学习
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关闭

推荐上一条 /2 下一条