首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >“通过赋值传递”是什么意思?

“通过赋值传递”是什么意思?
EN

Stack Overflow用户
提问于 2018-05-26 01:40:11
回答 1查看 4K关注 0票数 9

下面是我对java和python中传递的类型和参数的理解:在java中,有原始类型和非原始类型。前者不是宾语,后者是宾语。在python中,它们都是对象。

在java中,参数是通过值传递的,因为:原始类型会被复制然后传递,所以它们肯定是通过值传递的。非基元类型通过引用传递,但引用(指针)也是值,因此它们也是通过值传递的。在python中,唯一的区别是“基本类型”(例如,数字)不会被复制,而只是简单地作为对象。

基于官方文档,参数通过赋值传递。“通过赋值传递”是什么意思?java中的对象和python的工作方式一样吗?是什么导致了差异(在java中是通过值传递的,在python中是通过参数传递的)?上面有什么错误的理解吗?

EN

回答 1

Stack Overflow用户

发布于 2019-12-04 23:28:32

类似于在C#中通过值传递引用类型。

文档:https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/passing-reference-type-parameters#passing-reference-types-by-value

代码演示:

代码语言:javascript
复制
# mutable object
l = [9, 8, 7]


def createNewList(l1: list):
    # l1+[0] will create a new list object, the reference address of the local variable l1 is changed without affecting the variable l
    l1 = l1+[0]


def changeList(l1: list):
    # Add an element to the end of the list, because l1 and l refer to the same object, so l will also change
    l1.append(0)


print(l)
createNewList(l)
print(l)
changeList(l)
print(l)

# immutable object
num = 9


def changeValue(val: int):
    # int is an immutable type, and changing the val makes the val point to the new object 8, 
    # it's not change the num value
    value = 8


print(num)
changeValue(num)
print(num)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50534394

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档