• Python函数传递参数


    严格来讲,python中并不存在值传递和引用传递的说法,准确地说,Python 的参数传递是赋值传递 (pass by assignment),或者叫作对象的引用传递(pass by object reference),使用这两个说法只是为了更好地联系已经学过的内容,方便进行类比分析。

    在 Python 中:

    1、变量的赋值,只是表示让变量指向了某个对象,并不表示拷贝对象给变量;而一个对象,可以被多个变量所指向。

    2、可变对象(列表,字典,集合等等)的改变,会影响所有指向该对象的变量。

    3、对于不可变对象(字符串、整型、元组等等),所有指向该对象的变量的值总是一样的,也不会改变。但是通过某些操作(+= 等等)更新不可变对象的值时,会返回一个新的对象。

    def fun(lst, num, string):
        lst += ['yes']
        num += 1
        string += 'abc'
    
    
    lst = list('hello')
    num = 100
    string = 'def'
    
    print('befor:')
    print(lst, num, string)
    fun(lst, num, string)
    print('after:')
    print(lst, num, string)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    输出:

    befor:
    ['h', 'e', 'l', 'l', 'o'] 100 def
    after:
    ['h', 'e', 'l', 'l', 'o', 'yes'] 100 def
    
    • 1
    • 2
    • 3
    • 4

    从中可以看到,对列表的修改是作用在原对象上的,而对数字,字符串的修改不是直接作用在原对象上的。

    再看例子:

    def my_func4(l2):
        l2 = l2 + [666]
      
    l1 = [1, 2, 3]
    
    print('befor:')
    print(l1)
    print('after:')
    my_func4(l1)
    print(l1)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    输出:

    befor:
    [1, 2, 3]
    after:
    [1, 2, 3]
    
    • 1
    • 2
    • 3
    • 4

    分析:

    my_func4赋值语句左边的l2是新建立的,右边的l2是传入的,因为赋值符号(=)会产生新的对象,所以这个值并不会返回

    如果要拿到修改后的值,则需要使用return进行返回:

    def my_func5(l2):
      l2 = l2 + [4]
      return l2
    
    l1 = [1, 2, 3]
    
    print('befor:')
    print(l1)
    print('after:')
    l1 = my_func5(l1)
    print(l1)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    执行结果:

    befor:
    [1, 2, 3]
    after:
    [1, 2, 3, 4]
    
    • 1
    • 2
    • 3
    • 4

    参考内容:

    https://www.toutiao.com/article/6884789411372859918/?wid=1700120213662

    https://blog.csdn.net/weixin_41798450/article/details/89306399

  • 相关阅读:
    python 小案例96
    单载波频域均衡matlab仿真,包括卷积编码维特比译码,矩阵交织,QPSK调制解调,导频插入,MMSE-FDE频域均衡
    SQL Server 数据库之备份和恢复数据库
    Linux shell编程学习笔记26:stty(set tty)
    修改hugo新建post的默认信息(front matter)
    8位ADC是256还是255?
    1110 区块反转 – PAT乙级真题
    Docker 搭建 Nexus3 私服 | 基本操作
    XXL-JOB 分布式任务调度中心搭建
    Python实现深度森林(Deep Forest)分类模型(deepforest分类算法)项目实战
  • 原文地址:https://blog.csdn.net/weixin_43589323/article/details/134443797