Python 函数的使用和内嵌函数

函数定义与调用

  1. 使用 def 关键字进行函数的定义
  2. 使用.doc 或 help() 调用参数文档
  3. 对于函数的参数,为了避免出错,常常赋予初默认值
  4. 收集参数 *params
""""
函数
"""

def MyFirstFunction():
    print("123")


MyFirstFunction()


def MySecondFunction(name):
    """函数name叫做形参"""  # 函数文档
    print(name, " , I love you !")


MySecondFunction("丫头")
print(MySecondFunction.__doc__)  # 调用函数文档
print(help(MySecondFunction))  # 调用函数文档


def add(number1, number2):
    return number1 + number2


print(add(519, 1))


def say(name="蛮吉", s="奇衡三"):  # 赋予默认值
    print(name, "->", s)


say()
say(s="白落提、丰和、英宋、桓泽金、广秀", name="幽弥狂")  # 对应参数名


def test1(*params):  # 收集参数
    print(len(params), " ", params[0])


test1('w', 2, 3, "hhh")


def test2(*params, exp):
    print(len(params), " ", exp)


test2(1, 2, 3, "h", exp=1)  # 为防止出错,通常给予收集参数后的参数默认值

输出:

123
丫头  , I love you !
函数name叫做形参
Help on function MySecondFunction in module __main__:

MySecondFunction(name)
    函数name叫做形参

None
520
蛮吉 -> 奇衡三
幽弥狂 -> 白落提、丰和、英宋、桓泽金、广秀
4   w
4   1

函数返回值与global关键字

  1. 返回多个值时,默认打包返回元组
  2. 局部变量与全局变量
  3. 可以使用global关键字在函数内部指定变量为全局变量
"""
函数返回值与global关键字
"""
def back():
    return [1, 2, 3, "hello"]


def function():
    return 'hello', "laowang"  # 默认打包,返回元组


print(back())
print(function())


def f1():
    number = 5  # 局部变量number
    print(number)


def f2():
    global number  # 指定number指的是全局变量number
    number = 10
    print(number)


number = 1  # 全局变量number
f1()
f2()

输出:

[1, 2, 3, 'hello']
('hello', 'laowang')
5
10

函数的内嵌

  1. 内嵌函数只在函数内生效,在函数外无效
  2. 当外函数被调用时,内嵌函数才运转

def function1():
    print('function1正在被调用')

    def function2():  # 内嵌函数function2只能在function1内使用
        print('function2正在被调用')

    function2()


function1()  # 当function1被调用的时候,function2会被调用
# function2()  # 报错,function2没有被定义

输出:

function1正在被调用
function2正在被调用

闭包

def function(x):
    def f(y):
        return x*y
    return f


a=function(2)  # a其实是一个函数
print(a(3))
print(function(3)(4))


def function1():
    x=5  # 对于内嵌函数f(),变量x相当于局部变量,会被屏蔽起来,不可被访问
    def f():
        x*=x  #报错 local variable 'x' referenced before assignment
        return x
    return f()


def function2():
    x = [5]

    def f():
        x[0] *= x[0]  # 借助容器
        return x[0]

    return f()


def function3():
    x = 5

    def f():
        nonlocal x  # 借助关键字nonlocal,强制声明变量x不是局部变量
        x *= x
        return x

    return f()


print(function2())
print(function3())

输出:

6
12
25
25

匿名函数、filter()、map()

  1. 匿名函数:使用lambda关键字
  2. filter():过滤器,内置两个参数,第一个是函数或None,第二个是可迭代序列
  3. map():映射,内置两个参数,第一个是函数或None,第二个是可迭代序列
"""
匿名函数 lambda关键字 
filter(函数,可迭代序列)
map(函数,可迭代序列)
"""
def odd(number):
    return number % 2


filter(odd, range(10))  # 过滤器
l1 = list(filter(odd, range(10)))
print(l1)
l2 = list(map(lambda x: x ^ 2, range(5)))  # 映射
print(l2)

输出:

[1, 3, 5, 7, 9]
[2, 3, 0, 1, 6]

疑问

"""
内嵌函数的疑问
"""


def function0(x):
    def f(y):
        return x * y

    return f


def function1():
    x = [5]

    def f():
        x[0] *= x[0]
        return x[0]

    return f()


def function2():
    x = [5]

    def f():
        x[0] *= x[0]
        return x[0]

    return f


print(function0(5)(5))  # 25
print(function1())  # 25
print(function2())  # function function2.<locals>.f at 0x0000024C94C6BAE8>

输出:

25
25
<function function2.<locals>.f at 0x000001D75A4CBAE8>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值