类
#coding=utf-8
class Person:
'''Represents a person.'''
population = 0
def __init__(self,name):#相当于类的构造函数
'''Initiatizes the person's date.'''
self.name = name
print '(Initializing %s)' % self.name
Person.population += 1
def __del__(self):#相当于类的析构函数
'''I am dying.'''
print '%s says bye.' % self.name
def sayHi(self):
'''Greeting by the person.
Really.That all it does.'''
print '''Hi,My name is %s''' % self.name
def howmany(self):
'''Print the current population.'''
if Person.population == 1:
print 'I am the only person.'
else:
print 'We have %d person here.' % Person.population
swaroop = Person('swaroop')
swaroop.sayHi()
swaroop.howmany()
kalam = Person('kalam')
kalam.sayHi()
kalam.howmany()
swaroop.sayHi()
swaroop.howmany()
结果:
C:\Python27\python.exe D:/PyTest_one/test.py
(Initializing swaroop)
Hi,My name is swaroop
I am the only person.
(Initializing kalam)
Hi,My name is kalam
We have 2 person here.
Hi,My name is swaroop
We have 2 person here.
kalam says bye. #注意析构函数的顺序
swaroop says bye.
Process finished with exit code 0
类继承:
class schoolMember:
'''Represents any school Member.'''
def __init__(self,name,age):
self.name = name
self.age = age
print '(Initialized SchoolMember: %s)' % self.name
def tell(self):
'''Tell my details.'''
print 'Name:"%s", Age:"%s"' % (self.name,self.age)
class teacher(schoolMember):
'''Represents a teacher.'''
def __init__(self,name,age,salary):
schoolMember.__init__(self,name,age)
self.salary = salary
print '(Initializing the teacher:%s)' %self.name
def tell(self):
schoolMember.tell(self)
print 'Salary: "%d"' % self.salary
class student(schoolMember):
'''Represents the students.'''
def __init__(self,name,age,Mark):
schoolMember.__init__(self,name,age)
self.Mark = Mark
print '(Initialing the student:%s)' %self.name
def tell(self):
schoolMember.tell(self)
print 'Mark: "%d"' % self.Mark
t = teacher('Mrs.Zhang',38,5888)
s = student('zhang',18,2000)
print
members = [t,s]
for member in members:
member.tell()
结果:
C:\Python27\python.exe D:/PyTest_one/test.py
(Initialized SchoolMember: Mrs.Zhang)
(Initializing the teacher:Mrs.Zhang)
(Initialized SchoolMember: zhang)
(Initialing the student:zhang)
Name:"Mrs.Zhang", Age:"38"
Salary: "5888"
Name:"zhang", Age:"18"
Mark: "2000"
Process finished with exit code 0
文件操作:
# coding=utf-8
poem = '''\
Programing is fun
When the work is done
if your wanna make your work also fun:
use python!
'''
f = file('poem.txt','w')#若不存在自动创建
f.write(poem)
f.close()
f = file('poem.txt')#默认模式为read
while True:
line = f.readline()
if len(line) == 0:
break
print line
f.close()
存储与去存储:
# coding=utf-8
import cPickle as p #给模块一个新名字
shoplistfile = 'shoplist.date'
shoplist = ['apple','mango','carrot']
f = file(shoplistfile,'w') #打开文件
p.dump(shoplist,f)#往该文件里写数据
f.close()
del shoplist#删除该程序中的shoplist变量
f = file(shoplistfile)#打开文件
storedlist = p.load(f)#下载文件中的数据
print storedlist
异常:
#引发异常
# coding=utf-8
class ShortInputExcept(Exception):
'''A user-defined exception class'''
def __init__(self,length,atleast):
Exception.__init__(self)
self.length = length
self.atleast = atleast
try:
s = raw_input('Enter something-->')
if len(s)<3:
raise ShortInputExcept(len(s),3)
except EOFError:
print 'Why did you do an EOF to me?'
except ShortInputExcept,x:#x为ShotInputExcept的一个实例,或者except ShortInputException as x
print 'ShortInputException: The input was of length %d, \
was expecting at least %d' % (x.length,x.atleast)
else:
print 'No exception was raised.'
异常发生与否的情况下都关闭文件
# coding=utf-8
import time
try:
f = file('poem.txt')
while True: # our usual file-reading idiom
line = f.readline()
if len(line) == 0:
break
time.sleep(2)
print line,#多次输出不换行
finally:
f.close()
print 'Cleaning up...closed the file'
#问题:系统控制台执行时出问题:
C:\Users\Administrator>python D:\PyTest_one\test.py
Traceback (most recent call last):
File "D:\PyTest_one\test.py", line 3, in
f = open('poem.txt')
IOError: [Errno 2] No such file or directory: 'poem.txt'
模块:
sys
# coding=utf-8
import sys
def readfile(filename):
'''Print a file to the standard output.'''
f = file(filename)
while True:
line = f.readline()
if len(line) == 0:
break
print line, # notice comma
f.close()
if len(sys.argv) < 2:
print 'No action specified.'
sys.exit()
if sys.argv[1].startswith('--'):#如果第二个参数是以--开头
option = sys.argv[1][2:]#选择--之后的字符
if option == 'version':
print 'Version 1.2'
elif option == 'help':
print '''\
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help'''
else:
print 'Unknown option.'
sys.exit()
else:
for filename in sys.argv[1:]:#如果后面直接跟的是文件名,则输出
readfile(filename)
结果:
C:\Users\Administrator>python D:\PyTest_one\test.py --help
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--version : Prints the version number
--help : Display this help
C:\Users\Administrator>python D:\PyTest_one\test.py D:\PyTest_one\poem.txt
Programing is fun
When the work is done
if your wanna make your work also fun:
use python!
查询python版本信息:
C:\Users\Administrator>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> sys.version
'2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (Intel)
]'
>>> sys.version_info
sys.version_info(major=2, minor=7, micro=12, releaselevel='final', serial=0)
模块: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.path.split()函数返回一个路径的目录名和文件名。
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
● os.path.isfile()和os.path.isdir()函数分别检验给出的路径是一个文件还是目录。类似地,os.
path.exists()函数用来检验给出的路径是否真地存在。
结果:
C:\Users\Administrator>python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:19:22) [MSC v.1500 32 bit (
Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> os.name
'nt'
>>> os.getcwd
>>> os.getcwd()
'C:\\Users\\Administrator'
>>> os.listdir('C:\\Users\\Administrator')
['.aliyun', '.android', '.idlerc', '.ipynb_checkpoints', '.ipython', '.jupyter',
'.oracle_jre_usage', '.PyCharm2016.3', '.WebStorm10', 'AppData', 'Application D
ata', 'Contacts', 'Cookies', 'Desktop', 'Documents', 'Downloads', 'fancy', 'Favo
rites', 'Funshion', 'FunShion.ini', 'hsKfLshPLQ9', 'IntelGraphicsProfiles', 'Lin
ks', 'Local Settings', 'Music', 'My Documents', 'NetHood', 'NTUSER.DAT', 'ntuser
.dat.LOG1', 'ntuser.dat.LOG2', 'NTUSER.DAT{bbed3e3b-0b41-11e3-8249-d6927d06400b}
.TM.blf', 'NTUSER.DAT{bbed3e3b-0b41-11e3-8249-d6927d06400b}.TMContainer000000000
00000000001.regtrans-ms', 'NTUSER.DAT{bbed3e3b-0b41-11e3-8249-d6927d06400b}.TMCo
ntainer00000000000000000002.regtrans-ms', 'ntuser.ini', 'Pictures', 'PrintHood',
'qms-bmh1.bmp', 'qms-bmh2.bmp', 'qms-bmh3.bmp', 'quartus2.ini', 'quartus2.qreg'
, 'quartus_full_rules_file.txt', 'quartus_web_rules_file.txt', 'Recent', 'Saved
Games', 'Searches', 'SelfFiles.pfx', 'SendTo', 'Templates', 'Untitled.ipynb', 'u
ntitled.txt', 'Untitled1.ipynb', 'Videos', '\xa1\xb8\xbf\xaa\xca\xbc\xa1\xb9\xb2
\xcb\xb5\xa5']
>>> os.system('exit')
0
>>> os.linesep
'\r\n'
>>> os.path.split('D:\\PyTest_one\\test.py')
('D:\\PyTest_one', 'test.py')
>>> os.path.exists('D:\\PyTest_one')
True
其他知识:
#列表综合:
# coding=utf-8
listone = [2,3,4]
listtwo = [2*i for i in listone if i>2]
print listtwo
#结果:
C:\Python27\python.exe D:/PyTest_one/test.py
[6, 8]
Process finished with exit code 0
#在函数中接受元组和列表:
def powersum(power, *args):
'''Return the sum of each argument raised to specified power.'''
total = 0
for i in args:
total += pow(i, power)#返回i的power次方
return total
print powersum(2,3,4)#多余的函数参数都会作为一个元组存储在args中
print powersum(2,5,6)
#结果:25 61
#lambda形式返回函数
# coding=utf-8
def make_repeater(n):
return lambda s:s*n
twice = make_repeater(2)
print twice(2)
print twice('wwe')
#结果:
4
wwewwe
#exec和eval语句
# coding=utf-8
exec 'print "HELLO WORLD"'#计算字符串或文件中的Pyhton语句
print eval('2*3')#计算字符串或文件中的有效表达式
assert语句:
mylist = ['item']
assert len(mylist) >= 1
mylist.pop()#移除列表中最后一个元素
print mylist
assert len(mylist) >1#引发AssertionError错误