zoukankan      html  css  js  c++  java
  • Python中函数参数传递问题

    先上两个例子:

    http://python.jobbole.com/85231/

    a = 1
    def fun(a):
        a = 2
    fun(a)
    print a  # 结果为1

    fun(a)中的a,可以看做函数中的形参,可以用任何字符代替:fun(aaa)

    a = []
    def fun(a):
        a.append(1)
    fun(a)
    print a  # 结果为 [1]

    所有的变量都可以理解是内存中一个对象的“引用”,或者,也可以看似c中void*的感觉。

    这里记住的是类型是属于对象的,而不是变量。而对象有两种,“可更改”(mutable)与“不可更改”(immutable)对象。在python中,strings, tuples, 和numbers是不可更改的对象,而list,dict等则是可以修改的对象。(这就是这个问题的重点)

    当一个引用传递给函数的时候,函数自动复制一份引用,这个函数里的引用和外边的引用没有半毛关系了.所以第一个例子里函数把引用指向了一个不可变对象,当函数返回的时候,外面的引用没半毛感觉.而第二个例子就不一样了,函数内的引用指向的是可变对象,对它的操作就和定位了指针地址一样,在内存里进行修改.

    http://blog.csdn.net/crazyhacking/article/details/16114897


    看下面几个例子:

    >>> def modifier(number,string,list):
        number = 5
        string = 'GoodBye'
        list = [4,5,6]
        print "Inside:", number,string,list
    
        
    >>> num = 10
    >>> string = 'Hello'
    >>> list = [1,2,3]
    >>> print 'Before:', num, string, list
    Before: 10 Hello [1, 2, 3]
    >>> modifier(num,string,list)
    Inside: 5 GoodBye [4, 5, 6]
    >>> print 'After:', num, string, list
    After: 10 Hello [1, 2, 3]
    >>> def modifier(list,dict):
        list[0] = 10
        dict['a'] = 10
        print 'Inside list = %s, dict = %s' %(list,dict)
    
    >>> dict = {'a':1,'b':2,'c':3}
    >>> list = [1,2,3,4,5]
    >>> print 'Before list = %s, dict = %s' %(list,dict)
    Before list = [1, 2, 3, 4, 5], dict = {'a': 1, 'c': 3, 'b': 2}
    >>> modifier(list,dict)
    Inside list = [10, 2, 3, 4, 5], dict = {'a': 10, 'c': 3, 'b': 2}
    >>> print 'After list = %s, dict = %s' %(list,dict)
    After list = [10, 2, 3, 4, 5], dict = {'a': 10, 'c': 3, 'b': 2}
    >>> def swap(list):
        temp = list[0]
        list[0] = list[1]
        list[1] = temp
    
        
    >>> list = [10,20]
    >>> list
    [10, 20]
    >>> swap(list)
    >>> list
    [20, 10]

    http://blog.chinaunix.net/uid-20937170-id-3275808.html

    dd

  • 相关阅读:
    腾讯收购的《部落冲突》开发商有多牛?(这几个哥们真牛,什么技术都会,还能做出工业级的产品)
    人类最强大的一句话,可能就是三个字:我不要!
    Qt发展历史及其特点简介(没有哪一种方案能够独霸Windows)
    SpringMVC入门
    23种设计模式
    .NET序列化的一点技巧(附Demo)
    系统分层演变
    MVC程序中实体框架的连接恢复和命令拦截
    Mocha JavaScript TDD
    小型网站快速建设
  • 原文地址:https://www.cnblogs.com/hanggegege/p/5823337.html
Copyright © 2011-2022 走看看