Python2和Python3的差异

Python3的改进

  • print成为函数

  • print(*objectssep=' 'end='\n'file=sys.stdoutflush=False)
  • 主要用于打印输出
    • objects -- 复数,表示可以一次输出多个对象。输出多个对象时,需要用 , 分隔。
    • sep -- 用来间隔多个对象,默认值是一个空格。
    • end -- 用来设定以什么结尾。默认值是换行符 \n,我们可以换成其他字符串。
    • file -- 要写入的文件对象。
    • flush -- 输出是否被缓存通常决定于 file,但如果 flush 关键字参数为 True,流会被强制刷新
    • import time
      
      print("---Loading 效果---")
      
      print("Loading", end="")
      for i in range(20):
          print(".", end='', flush=True)
          time.sleep(0.5)
      print('a', 1, sep='=')
      View Code

       


  • 编码问题,Python3不再有unicode对象,默认str就是unicode

    • 在Python2中使用中文需要前面加u,u'中文',而在Python3字符串默认就是unicode,不需要考虑编码问题
    • 简单来说就是,unicode是给人看的,主要用来操作,而字节串是用于机器传输、保存等
    • #字符串编码成字节串,默认是utf-8
      s = '中文'
      print(s.encode())
      View Code

  • 除法变化,python3返回浮点数

    • 在Python2,除法会整数截断,得到整数部分;例:5 / 2 = 2

  • 类型注释(type hint),帮助ide实现类型检查

    • 在程序中添加类型提示,配合mypy(静态类型检查器), 不运行程序,就可以检查程序中参数或返回值的类型
    • # 参数name后面跟了:str 代表name期望是str类型
      # 参数括号后面跟了->str代表返回类型为str类型
      def greeting(name: str) -> str:
          return 'Hello ' + name
      x: str = 'xxx' # 声明一个变量为str类型
      greeting(x) # Hello xxx
      greeting(123) # TypeError: can only concatenate str (not "int") to str
      View Code

  • 优化的super()方便直接调用父类函数

  • class Base(object):
    
        def hello(self):
            print('hello')
    
    class C(Base):
    
        def hello(self):
            super().hello()
    
    
    c = C()
    c.hello()
    View Code

  • 高级解包操作,a, b, *rest = range(10)


  • Keyword only arguments 限定关键字参数

    • 比如参数比较多,传参需要显示传入(在*号之后的参数只能通过关键字参数传递的叫keyword-only参数)

    • def add(a, b, *, c):  # c就是限定关键字参数
          return a + b +c
      
      add(1, 2, c=3)
      View Code

  • Chained exceptions, Python3 重新抛出异常不会丢失栈信息  


  • 一切返回迭代器 range, zip, map, dict.values etc. are all iterators.


  • 生成的pyc文件统一放到__pycahe__中

  


Python3新增

  • yield from 链接子生成器

  • asyncio内置库,aysnc/wait原生协程

  • 新的内置库:enum,mock,asyncio,ipadress,concurrent.futures等

 


兼容Python2/3的工具  

  • six模块

  • 2to3等工具转换代码

  • __future__

posted @ 2020-05-10 20:40  Ming|Zhao  阅读(193)  评论(0)    收藏  举报