• 值传递和引用传递


    根据实际参数的类型不同,可以将实际参数的值传递给形式参数,或将实际参数的引用传递给形式参数。

    其中,当实际参数为不可变对象时,进行的时值传递;当实际参数为可变对象时,进行的时引用传递。

    值传递和引用传递区别:

    值传递后,改变形式参数的值,实际参数的值不变;

    引用传递后,改变行是参数的值,实际参数的值也一同改变。

    代码:

     1 def demo(obj):
     2     print("原来的值:",obj)
     3     obj += obj
     4 
     5 #调用函数
     6 print("="*5 + "值传递" + "=" *5)
     7 mot = '哈哈哈'
     8 print("执行函数前:",mot)
     9 demo(mot)
    10 print("执行函数后",mot)
    11 
    12 print("="*5 + "引用传递" + "=" *5)
    13 list1 = ["11","22","33"]
    14 print("执行函数前:",list1)
    15 demo(list1)
    16 print("执行函数后",list1)

    结果:

    D:python_workvenvScriptspython.exe D:/python_work/test.py
    =====值传递=====
    执行函数前: 哈哈哈
    原来的值: 哈哈哈
    执行函数后 哈哈哈
    =====引用传递=====
    执行函数前: ['11', '22', '33']
    原来的值: ['11', '22', '33']
    执行函数后 ['11', '22', '33', '11', '22', '33']
    
    Process finished with exit code 0

    参考:

    int,string,float,tuple 不可变对象

    dict,set,list 可变对象

    应用场景:

    待了解,补充

  • 相关阅读:
    codeforces A. Chess Placing
    codeforces E. Cyclic Components
    poj1930(小数化分数)
    hdu4497 (正数分解定理+排列组合)
    cf 466 div.2 A. Points on the line
    hdu1576(扩展欧几里得求逆元板子)
    逆元(转载)
    stiring 数..........
    逆元
    矩阵 构造 模板
  • 原文地址:https://www.cnblogs.com/leisurelyRD/p/11973928.html
Copyright © 2020-2023  润新知