python函数是对python语句的封装,到达一次编写,多处、多次运行的目的。
1.1 def
用法
def 函数名(参数1,参数2,...,参数n):
函数主体语句
return 值
描述
def语句末尾跟冒号结束
函数主体语句需要缩进
参数可以为0或1或多个
return语句返回值,如果没有return则返回None。
1.2 def函数定义和调用
python函数的def语句在模块导入时会运行,将函数对象赋值给函数名,函数主体只有在函数调用时执行。
def语句可嵌套在if语句中。
python函数名可以赋值给变量。
python通过函数名()来调用函数。括号()为调用表达式。
示例
'''
文件名:functest.py
'''
def nestdef(test):
if test:
def ftest(name):
print('ftest')
print('hello ',name)
else:
def ftest(name):
print('notest')
print('hello ',name)
return ftest
# def函数嵌套以及赋值
>>> path=r'E:\documents\F盘'
>>> import os
>>> os.chdir(path)
>>> from functest import nestdef
>>> S='梯阅线条'
>>> f0=nestdef(0)
>>> f1=nestdef(1)
>>> f0(S)
notest
hello 梯阅线条
>>> f1(S)
ftest
hello 梯阅线条
>>> f3=f1
>>> f3(S)
ftest
hello 梯阅线条
1.3 python多态
python多态是相同一个操作的效果取决于被操作对象的类型,如果被操作对象不支持则自动抛错。
比如,*操作符对于数字为乘法,对于字符为重复。
示例
# *操作符,数字对应乘法,字符对应重复
>>> def times(x,y):
return x*y
>>> times(2,3)
6
>>> times('tyxt',2)
'tyxttyxt'
# 查找序列的交集
>>> def intersects(seq1,seq2):
return [x for x in seq1 if x in seq2]
>>> S1,S2='tyxt','txt'
>>> intersects(S1,S2)
['t', 'x', 't']
>>> intersects((1,2,3),[2,3,5,6,7])
[2, 3]
更多内容参考python知识分享或软件测试开发目录。