五、
>>> 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