• python摸爬滚打之day010----函数进阶


    1、函数动态传参

     *args : 将所有的位置参数打包成一个元组的形式. 

     **kwargs : 将所有的关键字参数打包成一个字典的形式. 

     形参的接收顺序:    位置参数 > *args > 默认值参数> **kwargs.

    2、命名空间

     命名空间: 在python解释器执行后, 内存中开辟的一块用于存放变量名和值对应关系的一个空间.

     分类:

          内置命名空间: python自己提供的一些方法, print(), int()...

          全局命名空间: .py文件中, 函数外声明的变量等...

          局部命名空间: 函数或类中声明的变量...

     命名空间的加载顺序:  内置命名空间  >> 全局命名空间  >> 局部命名空间

             取值顺序: 局部命名空间  >>  全局命名空间  >> 内置命名空间

    3、作用域

     全局作用域:内置命名空间 + 全局命名空间

     局部作用域: 仅在函数或类内部的作用域

    4、global , nonlocal

     global: 声明全局变量. 声明不使用局部作用域中的变量, 直接用全局作用域中的变量. 

    1 a = 10
    2 def outer():
    3     a = 100
    4     def inner():
    5         global a       # 不是改变inner()外部的a,而是改变全局作用域中的a(即最外边的a)
    6         a = 200
    7     inner()
    8 outer()
    9 print(a)     # 200
    global

     nonlocal: 声明全局内某层函数外的局部变量.  声明在局部作用域中,调用父级命名空间中的变量.

     1 a = 10
     2 def outer():
     3     a = 100
     4     print("nonlocal之前",a)         #  100
     5     def inner():
     6         nonlocal a        # 仅改变inner()父级的局部作用域.
     7         a = 200
     8     inner()
     9     print("nonlocal之后",a)         #  200
    10 outer()
    11 print(a)                                     # 10
    nonlocal

      注意: nonlocal 不能声明调用最外层(即全局作用域)的变量, 会直接报错.

     1 a = 10
     2 def outer():
     3     def inner():
     4         nonlocal a       # 不能找到最外层(即全局作用域)的变量
     5         a = 200
     6     inner()
     7 outer()
     8 
     9 
    10 
    11 #  会直接报错 : SyntaxError: no binding for nonlocal 'a' found
    nonlocal
  • 相关阅读:
    博客园美化-打赏代码
    苹果appID的获取方法
    简体、繁体相互转换
    iOS Socket编程(一)基本概念
    无线通信
    http与https通信
    iOS开发网络篇—发送GET和POST请求(使用NSURLSession)
    iOS开发网络篇—GET请求和POST请求的说明与比较
    iOS开发网络篇—HTTP协议
    Verify the Developer App certificate for your account is trusted on your device.
  • 原文地址:https://www.cnblogs.com/bk9527/p/9880058.html
Copyright © 2020-2023  润新知