zoukankan      html  css  js  c++  java
  • python返回值与局部全局变量

    Python 2.7.10 (default, Oct 14 2015, 16:09:02) 
    [GCC 5.2.1 20151010] on linux2
    Type "copyright", "credits" or "license()" for more information.
    >>> def fun1():
        return [1,2,3]
    
    >>> print(fun1)
    <function fun1 at 0xb71cfb8c>
    >>> a=fun1()
    >>> a
    [1, 2, 3]
    >>> def fun2():
        return 4,5,6
    
    >>> b=fun2()
    >>> b
    (4, 5, 6)
    >>> def fun3():
        print "hello woeld"
    
        
    >>> c=fun3()
    hello woeld
    >>> c
    >>> c
    >>> print(fun(3))
    
    Traceback (most recent call last):
      File "<pyshell#17>", line 1, in <module>
        print(fun(3))
    NameError: name 'fun' is not defined
    >>> type(c)
    <type 'NoneType'>
    >>> print(c)
    None
    >>> type(c)
    <type 'NoneType'>
    >>> 

    函数的返回值可以是一个列表或一个元组,如果没有return,那么仍然会返回一个NONE,类型那个为typenone,

    对于全局ii变量,我们在函数中只能进行引用,而不能进行修改

    局部在堆栈中分配,

     当我们你试图在函数中修改全局变量的时候,python会发生屏蔽,会在函数中发生屏蔽机制,额外创建一个临时变量,只能对临时变量进行修改

    但是我们可通过global关键子在函数中强制对全局变量进行修改

     1 >>> 
     2 >>> number=5
     3 >>> def fun6():
     4     global number
     5     number=10
     6     return number
     7 
     8 >>> fun6()
     9 10
    10 >>> print(num)
    11 10
    12 >>> print(number)
    13 10
    14 >>> 

    python函数还可以进行嵌套

    >>> 
    >>> def f1():
        print("fun1..")
        def fun2():
            print("fun2")函数作用范围同c/c++
        fun2()
    
        
    >>> f1()
    fun1..
    fun2
    >>> 

    函数都嵌套传参数,对于第一种方法,如果我们只是传了一个参数,那么会返回一个函数,表示需要想第二个函数传参数,

    简单的做法就是直接连续写两个括号传两个参数

     1 >>> def fun1(x):
     2     def fun2(y):
     3         return x*y
     4     return fun2
     5 
     6 >>> fun1()
     7 
     8 Traceback (most recent call last):
     9   File "<pyshell#108>", line 1, in <module>
    10     fun1()
    11 TypeError: fun1() takes exactly 1 argument (0 given)
    12 >>> fun1(5)
    13 <function fun2 at 0xb71cfb8c>
    14 >>> type(fun1(5))
    15 <type 'function'>
    16 >>> i=fun1(5)
    17 >>> i(10)
    18 50
    19 >>> fun1(3)(8)
    20 24

    对于python3.0之前,为了可以在局部对外部变量进行改变,因为list不是在堆栈山申请的,所以我们可以改变外部的list变量

    1 >>> def fun5():
    2     x=[5]
    3     def fun6():
    4         x[0]*=x[0]
    5         return x[0]
    6     return fun6()
    7 
    8 >>> fun5()
    9 25

    3.0之后可以只有 nonlocal 

    闭包就是内部函数可以使用外部的作用区间(不是全局的)进行引用,那么这个内部函数就被叫闭包

  • 相关阅读:
    函数式编程:用户登录和注册
    文件操作
    shell介绍
    函数返回值
    selenium 事件介绍
    Linux添加硬盘设备
    分布式系统中幂等性、at least once 和 at most once 问题
    HBase面试考点
    简单理解:数据库的一致性与四种隔离级别(+MySQL实现)
    大数据框架Hive优化方法
  • 原文地址:https://www.cnblogs.com/13224ACMer/p/6045487.html
Copyright © 2011-2022 走看看