1

Python 传值 or 传引用

 2 years ago
source link: https://blog.frytea.com/archives/622/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

Python 传值 or 传引用

January 19, 2022 • Read: 43 • 编程开发

本文首发于: https://blog.frytea.com/archives/622/

先说结论:python 不允许程序员选择采用传值还是传引用。

  • 如果函数收到的是一个 可变对象 (比如 字典 或者 列表 )的引用,就能修改对象的原始值--相当于通过 “传引用” 来传递对象。
  • 如果函数收到的是一个 不可变对象 (比如 数字字符 或者 元组 )的引用,就不能直接修改原始对象--相当于通过 “传值' 来传递对象。

在函数传值,或函数内部函数引用外部变量时,基本符合这个逻辑,比如:

def test_dect_out():
lvs = {}
num1 = 3
def lan():
lvs['sss'] = 4
num1 = 5
return lvs, num1
print(lvs, num1)
print(lan())
print(lvs, num1)
({'sss': 4}, 5)
{'sss': 4} 3

---------------------
Author: Frytea
Title: Python 传值 or 传引用
Link: https://blog.frytea.com/archives/622/
Copyright: This work by TL-Song is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK