下面是我对java和python中传递的类型和参数的理解:在java中,有原始类型和非原始类型。前者不是宾语,后者是宾语。在python中,它们都是对象。
在java中,参数是通过值传递的,因为:原始类型会被复制然后传递,所以它们肯定是通过值传递的。非基元类型通过引用传递,但引用(指针)也是值,因此它们也是通过值传递的。在python中,唯一的区别是“基本类型”(例如,数字)不会被复制,而只是简单地作为对象。
基于官方文档,参数通过赋值传递。“通过赋值传递”是什么意思?java中的对象和python的工作方式一样吗?是什么导致了差异(在java中是通过值传递的,在python中是通过参数传递的)?上面有什么错误的理解吗?
发布于 2019-12-04 23:28:32
类似于在C#中通过值传递引用类型。
代码演示:
# 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)https://stackoverflow.com/questions/50534394
复制相似问题