Python&&Python2.7与Python3的区别
类的继承语法
Python3
class Computer():
def __init__(self,cpu,memory,hard):
self.cpu = cpu
self.memory = memory
self.hard = hard
def computer_info(self):
print("This computer has " + self.cpu)
class Thinkpad(Computer):
def __init__(self,cpu,memory,hard):
super().__init__(cpu,memory,hard)
Python2.7
class Computer(object):
def __init__(self,cpu,memory,hard):
self.cpu = cpu
self.memory = memory
self.hard = hard
def computer_info(self):
print("This computer has " + self.cpu)
class Thinkpad(Computer):
def __init__(self,cpu,memory,hard):
super(Computer,self).__init__(cpu,memory,hard)
print的使用
Python3
>>> print("hello world!")
hello world!
Python2.7
>>> print "hello world!"
hello world!
模块取代
subprocess代替commands
Python3
>>> import subprocess
>>> b = subprocess.getstatusoutput('dir')
>>> print(b)
(0, ' 驱动器 C 中的卷是 我很重要\n 卷的序列号是 7464-B46A\n\n 34 个目录 17,351,016,448 可用字节')
>>>
Python2.7
>>> import commands
>>> b = commands.getstatusoutput('dir')
>>> print(b)
(0, ' 驱动器 C 中的卷是 我很重要\n 卷的序列号是 7464-B46A\n\n 34 个目录 17,351,016,448 可用字节')
>>>
函数取代
用input替换raw_input
Python3
$ vim 200111_print.py
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
name = input("Please input you name :")
age = input("Please input you age :")
salary = input("Please input you salary :")
print(
'''
------------------------------------
Personal infomation of %s:
Name : %s
Age : %s
Salary : %s
------------------------------------
''' % (name,name,age,salary))
Python2.7
$vi test3.py
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
name = raw_input(‘Please input your name :’)
age = raw_input(‘age:’)
job = raw_input(‘job’)
salary = raw_input(‘salary:’)
print type(age)
#age的类型为字符串,因为所有raw_input输入的类型默认都是字符串
print '''
personal information of %s:
name: %s
age : %s
job : %s
salary: %s
--------------------------------------------
''' %(name,name,age,job,salary)
错误使用引发的错误:
C:\Users\Administrator\Desktop\老男孩python8期\PY>python 200111_print.py
Traceback (most recent call last):
File "200111_print.py", line 4, in <module>
name = raw_input("Please input you name :")
NameError: name 'raw_input' is not defined
文件处理
文件读取
Python2.7
f = file('pi_digits.txt','r')
f.readline()
f.readline()
f.close()
Python3
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
filename = 'pi_digits.txt'
with open(filename) as file_object
lines = file_object.readlines()
for line in lines:
print(line.rstrip())
文件写入
Python2.7
f = file('pi_digits.txt','w')
f.write("the world")
f.close()
Python3
#!/usr/bin/env python
#_*_ coding:utf-8 _*_
filename = 'porgraming.txt'
with open(filename,'w') as file_object:
file_object.write("technology change world")