python2和python3差异对比

来源:互联网 发布:剪裁照片的软件 编辑:程序博客网 时间:2024/05/21 17:36

1. 获取用户输入
python2使用函数raw_input()
python3使用函数input()
2. 定义类
python2定义类需要在括号里写上object而python3不需要:

class  ClassName (object):    ...

python3定义类:

class  ClassName ():    ...

3. 子类继承
python2子类继承如下:

#父类Class Parent(object):    def __init__(self,attribute):#子类Class Child(Parent):    def __init__(self,attribute):        super(Child, self).__init__(attribute)
  • 在Python2中使用继承时,必需在定义父类时在括号内指定 object
  • 函数 super() 需要两个实参:子类名和对象 self

python3子类继承如下:

#父类Class Parent():    def __init__(self,attribute):#子类Class Child(Parent):    def __init__(self,attribute):        super().__init__(attribute)

4. urllib库的使用
Python 2.x 里的 urllib2 库在 Python 3.x 里,urllib2 改名为 urllib,并被分成一些子模块: urllib.request 、urllib.parse 和 urllib.error 。

python2.x使用 urllib实例:

from urllib import urlopen  html = urlopen("http://pythonscraping.com/pages/page1.html")print(html.read())

python3.x使用 urllib实例:

from urllib.reque st  import u rlopenhtml = urlopen("http://pythonscraping.com/pages/page1.html")print(html.read())
0 0
原创粉丝点击