Python2和Python3的区别

核心区别

1.Python2 默认编码方式ACSII,Python3默认编码utf-8

导致Python3的string只支持unicode的string,Python2支持str和unicode

2.Python3采用绝对路径方式进行import

避免Python2中导入标准库与绝对路径下的文件重名引发的问题

3.Python3只采用新式类,Python2有经典类和新式类

主要是多重继承的区别

新式类:采用就近原则

class NewStyleClassA(object):
    var = 'New Style Class A'


class NewStyleClassB(NewStyleClassA):
    pass


class NewStyleClassC(object):
    var = 'New Style Class C'


class SubNewStyleClass(NewStyleClassB, NewStyleClassC):
    pass


if __name__ == '__main__':
    print(SubNewStyleClass.mro())
    print(SubNewStyleClass.var)

[<class '__main__.SubNewStyleClass'>, <class '__main__.NewStyleClassB'>, <class '__main__.NewStyleClassA'>, <class '__main__.NewStyleClassC'>, <type 'object'>]
New Style Class A
View Code

经典类:采用 广度优先原则

class NewStyleClassA(object):
    var = 'New Style Class A'


class NewStyleClassB(NewStyleClassA):
    pass


class NewStyleClassC(NewStyleClassA)
    var = 'New Style Class C'


class SubNewStyleClass(NewStyleClassB, NewStyleClassC):
    pass


if __name__ == '__main__':
    print(SubNewStyleClass.mro())
    print(SubNewStyleClass.var)

[<class '__main__.SubNewStyleClass'>, <class '__main__.NewStyleClassB'>, <class '__main__.NewStyleClassC'>, <class '__main__.NewStyleClassA'>, <type 'object'>]
New Style Class C
View Code

4.Python3中使用更加严格的缩进

Python2中一个tab和8个空格是等价的,Python3要么都使用tab要么都是四个空格

 

参考链接

https://blog.csdn.net/pangzhaowen/article/details/80650478

https://www.cnblogs.com/blackmatrix/p/5630515.html

https://www.runoob.com/python/python-2x-3x.html

posted on 2020-03-03 10:35  喝了少不如不喝  阅读(324)  评论(0编辑  收藏  举报

导航