五、
>>> def hello():
print('123123')
>>> hello()
123123
>>> def hello1(v):
print(v)
return v
>>> a = hello1(123)
123
>>> a
123
>>> def hello2(v1, v2):
print(v1)
return v2
>>> b = hello2(1, 3)
1
>>> b
3
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
>>>def hello(hi='你好', name='Python'):
print('%s, %s!' % (hi, name))
>>> hello('Jonson')
Jonson, Python!
>>> hello('hi', 'Jonson')
hi, Jonson!
>>>hello(name='Jonson')
你好,Jonson!
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def hello(*tpl):
print(type(tpl))
print(tpl)
hello(1)
hello(1,2,3)
<class 'tuple'>
(1,)
<class 'tuple'>
(1, 2, 3)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def hello(*tpl,a,b=0):
print(tpl)
print('a:', a)
print('b:', b)
hello(1,2,3,a=5)
hello(1,2,3)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def change_para_dct(a, b=0, **adct):
print('adct:',adct)
print('a:', a)
print('b:', b)
change_para_dct(1, k=3, b=2, c=3)
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def change_para_dct(a, b=0, **adct):
print('adct:',adct)
print('a:', a)
print('b:', b)
change_para_dct(1, k=3, b=2, c=3)
>>>
adct: {'c': 3, 'k': 3}
a: 1
b: 2
>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def cube(name, **nature):
all_nature.update(nature)
print(name, "立方體的屬性:")
print('體積:', all_nature['x']*all_nature['y']*all_nature['z'])
print('顏色:', all_nature['color'])
print('重量:', all_nature['weight'])
cube('first')
cube('second', y=3,color='red')
cube('third',z=2,color='green',weight=10)
>>>
first 立方體的屬性:
體積:1
顏色:white
重量:1
second 立方體的屬性:
體積:3
顏色:white
重量:1
third 立方體的屬性:
體積:2
顏色:white
重量:10
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def mysum(a,b):
return a+b
print('拆解元組調用:')
print(mysum(*(3,4)))
print('拆解字典調用:')
print(mysum(**{'a':3,'b':4}))
>>>
拆解元組調用:
7
拆解字典調用:
7
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def change(aint, alst):
aint = 0
alst[0]=0
alst.append(4)
print('函數中aint:',aint)
print('函數中aist:',aint)
aint = 3
alst =[1,2,3]
print('調用前aint:',aint)
print('調用前alst:',alst)
change(aint, alst)
print('調用後aint:',aint)
print('調用後alst:',alst)
>>>
調用前aint: 3
調用前alst: [1, 2, 3]
函數中aint: 0
函數中aist: 0
調用後aint: 3
調用後alst: [0, 2, 3, 4]
>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def myfun():
a=0
a+=3
print('函數內a:',a)
a='external'
print('全局作用域a:',a)
myfun()
print('全局作用域a:',a)
>>>
全局作用域a: external
函數內a: 3
全局作用域a: external
>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
def myfun():
global a
a=0
a+=3
print('函數內a:',a)
a='external'
print('全局作用域a:',a)
myfun()
print('全局作用域a:',a)
>>>
全局作用域a: external
函數內a: 3
全局作用域a: 3
>>>
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
a='external'
def myfun():
a=0
a+=3
print('函數內a:',a)
print('全局作用域a:',a)
myfun()
print('全局作用域a:',a)
>>>
全局作用域a: external
函數內a: 3
全局作用域a: external
>>> 和全局變量定義的位置無關,只要函數內的變量不用global修飾就永遠是局部變量
>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
匿名函數
>>>
sum = lambda x,y:x+y
sum(2,3)
5
>>>
六、
class DemoInit:
def __init__(self,x,y=0):
self.x = x
self.y = y
def mycacl(self):
return self.x + self.y
dia = DemoInit(3)
print('調用mycacl方法的結果1:')
print(dia.mycacl())
dib = DemoInit(3,7)
print('調用mycacl方法的結果2:')
print(dib.mycacl())
>>> ================================ RESTART ================================
>>>
調用mycacl方法的結果1:
3
調用mycacl方法的結果2:
10
>>>
def coord_chng(x,y):
return (abs(x),abs(y))
class Ant:
def __init__(self,x=0,y=0):
self.x = x
self.y = y
self.disp_point()
def move(self,x,y):
x,y = coord_chng(x,y)
self.edit_point(x,y)
self.disp_point()
def edit_point(self,x,y):
self.x += x
self.y += y
def disp_point(self):
print("current pos:(%d, %d)" % (self.x, self.y))
ant_a = Ant()
ant_a.move(2,4)
ant_a.move(-9,6)
>>> ================================ RESTART ================================
>>>
current pos:(0, 0)
current pos:(2, 4)
current pos:(11, 10)
>>>
class Demo_Property:
class_name = "Demo_Property"
def __init__(self,x=0):
self.x = x
def class_info(self):
print('var value:', Demo_Property.class_name)
print('class var value:', self.x)
def chng(self,x):
self.x = x
def chng_cn(self,name):
Demo_Property.class_name = name
dpa = Demo_Property()
dpb = Demo_Property()
print('init twice instance')
dpa.class_info()
dpb.class_info()
print('modify instance var')
print('modify dpa instance var')
dpa.chng(3)
dpa.class_info()
dpb.class_info()
print('modify dpb instance var')
dpb.chng(10)
dpa.class_info()
dpb.class_info()
print('modify class var')
print('modify dpa class var')
dpa.chng_cn('dpa')
dpa.class_info()
dpb.class_info()
print('modify dpb instance var')
dpb.chng_cn('dpb')
dpa.class_info()
dpb.class_info()
>>> ================================ RESTART ================================
>>>
init twice instance
var value: Demo_Property
class var value: 0
var value: Demo_Property
class var value: 0
modify instance var
modify dpa instance var
var value: Demo_Property
class var value: 3
var value: Demo_Property
class var value: 0
modify dpb instance var
var value: Demo_Property
class var value: 3
var value: Demo_Property
class var value: 10
modify class var
modify dpa class var
var value: dpa
class var value: 3
var value: dpa
class var value: 10
modify dpb instance var
var value: dpb
class var value: 3
var value: dpb
class var value: 10
>>>
class DemoMthd:
def __init__(self,x=0):
self.x=x
@staticmethod
def static_mthd():
print('call static method')
@classmethod
def class_mthd(cls):
print('call class method')
DemoMthd.static_mthd()
DemoMthd.class_mthd()
dm = DemoMthd()
dm.static_mthd()
dm.class_mthd()
>>> ================================ RESTART ================================
>>>
call static method
call class method
call static method
call class method
>>>
類的繼承需要在類定以後加圓括號,圓括號內爲父類名,多個父類名之間用逗號隔開
重載只需在子類中直接定義函數就可以
七、
try:
...
except <異常名1>:
...
except <異常名2>:
...
else: #未觸發異常則執行該語句,該語句在未引發異常情況下得到執行
...
finally:#始終執行該語句,一般是爲了達到釋放資源等目的
...
try:
...
except IndexError:
...
try:
...
except:
...
finally:
...
except: 捕捉所有異常
except <異常名>:#捕獲指定異常
except (異常名1,異常名2): 捕獲異常名1或異常名2
except<異常名>as<數據>: 捕獲指定異常及附加的數據
except(異常名1,異常名2)as<數據>:#捕獲異常名1或者異常名2及異常的附加數據
當程序運行時引發了不能被捕獲的異常時仍然會中斷
捕獲所有異常,則出現任何錯誤都不會使程序中斷,但是同時捕獲所有異常,有時會使程序出現異常時,程序員不知所措,找不到問題所在。
異常處理的try語句也是可以嵌套的。
def add(x,y):
return x + y
if __name__ == "__main__":
try:
z = add(3,'wrqe')
print(z);
except:
print('error')
finally:
print('finish')
//------------------------------------------------------
def testTryFinally(index):
stulst = ["John", "Jenny", "Tom"]
af = open("my.txt", 'wt+')
try:
af.write(stulst[index])
except:
pass
finally:
af.close
print("File already had been closed!")
print('No IndexError...')
testTryFinally(1)
print('IndexError...')
testTryFinally(2)
ar = open("my.txt", 'r')
ss = ar.read()
print(ss)
//------------------------------------------------------
程序員還可以在python程序中使用raise語句來引發指定的異常,並向異常傳遞數據
程序員還可以自定義新的異常類型,例如對用戶輸入文本的長度有要求,則可以使用raise引發異常,以確保文本輸入的長度符合要求
使用raise引發異常的方式:
raise 異常名
raise 異常名,附加數據
raise 類型
def testRaise():
for i in range(5):
if i==2:
raise NameError
print(i)
print('end...')
testRaise()
>>> ================================ RESTART ================================
>>>
0
1
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/s13.py", line 7, in <module>
testRaise()
File "C:/Users/Administrator/Desktop/s13.py", line 4, in testRaise
raise NameError
NameError
def testRaise():
for i in range(5):
try:
if i==2:
raise NameError
except NameError:
print('Raise a NameError!')
print(i)
print('end...')
testRaise()
>>> ================================ RESTART ================================
>>>
0
1
Raise a NameError!
2
3
4
end...
>>>
assert <條件測試>,<異常附加數據> #其中異常附加數據是可選的
assert語句是簡化的raise語句,它引發異常的前提是其後面的條件測試爲假
assert語句一般用於在程序開發時測試代碼有效性
assert語句並不是總是運行的,只有python內置的一個特殊變量__debug__爲True時才運行,要關閉程序中的assert語句就使用python -O來運行程序
def testAssert():
for i in range(5):
try:
assert i<2
except AssertionError:
print('Raise a AssertionError!')
print(i)
print('end...')
testAssert()
>>> ================================ RESTART ================================
>>>
0
1
Raise a AssertionError!
2
Raise a AssertionError!
3
Raise a AssertionError!
4
end...
>>>
//自定義異常類
class RangeError(Exception):
def __init__(self,value):
self.value = value
def __str__(self):
return self.value
raise RangeError('Range Error!')
>>> ================================ RESTART ================================
>>>
Traceback (most recent call last):
File "C:/Users/Administrator/Desktop/s13.py", line 7, in <module>
raise RangeError('Range Error!')
RangeError: Range Error!
>>>
用PDB調試語句塊函數
import pdb
pdb.run("""
for i in range(3):
print(i)
""")
>>> ================================ RESTART ================================
>>>
> <string>(2)<module>()
(Pdb) n
> <string>(3)<module>()
(Pdb) c
0
1
2
>>>
用PDB調試函數
import pdb
def sum(maxint):
s=0
for i in range(maxint):
s+=i
return s
pdb.runcall(sum,10)
>>> ================================ RESTART ================================
>>>
> c:\users\administrator\desktop\s13.py(3)sum()
-> s=0
(Pdb) n
> c:\users\administrator\desktop\s13.py(4)sum()
-> for i in range(maxint):
(Pdb) c
>>>
測試testmod()
def grade(sum):
"""
>>> grade(100)
'greate'
>>> grade(80)
'nice'
>>> grade(65)
'good'
>>> grade(10)
'worse'
"""
if sum > 90:
return 'greate'
if sum > 80:
return 'nice'
if sum > 60:
return 'good'
if sum < 60:
return 'worse'
if __name__ == '__main__':
import doctest
doctest.testmod()
>>> ================================ RESTART ================================
>>>
**********************************************************************
File "C:/Users/Administrator/Desktop/s13.py", line 5, in __main__.grade
Failed example:
grade(80)
Expected:
'nice'
Got:
'good'
**********************************************************************
1 items had failures:
1 of 4 in __main__.grade
***Test Failed*** 1 failures.
測試testfile()
>>> from a7_13 import grade
>>> grade(100)
'greate'
>>> grade(80)
'nice'
>>> grade(65)
'good'
>>> grade(10)
'worse'
import os
os.chdir('d:\\lx\c7')
import doctest
doctest.testfile('mytest.txt')
或者命令提示符下:
d:
cd lx\c7
python -m doctest a7_12.py
python -m doctest mytest.txt