>>> 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')

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

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)

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

print('a:', a)

print('b:', b)

change_para_dct(1, k=3, b=2, c=3)

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

print('a:', a)

print('b:', b)

change_para_dct(1, k=3, b=2, c=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 立方体的属性:

second 立方体的属性:

third 立方体的属性:

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
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)

>>>

>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

def myfun():

a=0

a+=3

print('函数内a:',a)

a='external'

print('全局作用域a:',a)

myfun()

print('全局作用域a:',a)

>>>

>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

def myfun():

global a

a=0

a+=3

print('函数内a:',a)

a='external'

print('全局作用域a:',a)

myfun()

print('全局作用域a:',a)

>>>

>>>

>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

a='external'

def myfun():

a=0

a+=3

print('函数内a:',a)

print('全局作用域a:',a)

myfun()

print('全局作用域a:',a)

>>>

>>> 和全局变量定义的位置无关，只要函数内的变量不用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 ================================

>>>

3

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及异常的附加数据

return x + y

if __name__ == "__main__":

try:

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('No IndexError...')

testTryFinally(1)

print('IndexError...')

testTryFinally(2)

ar = open("my.txt", 'r')

print(ss)

//------------------------------------------------------

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!

>>>

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

>>>

import pdb

def sum(maxint):

s=0

for i in range(maxint):

s+=i

return s

pdb.runcall(sum,10)

>>> ================================ RESTART ================================

>>>

-> s=0

(Pdb) n

-> for i in range(maxint):

(Pdb) c

>>>

"""

'greate'

'nice'

'good'

'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 ================================

>>>

**********************************************************************

Failed example:

Expected:

'nice'

Got:

'good'

**********************************************************************

***Test Failed*** 1 failures.

'greate'

'nice'

'good'

'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