python笔记-函数的参数传递

Created at 2020-10-15 Updated at 2021-12-12 Category python Tag python

在Python中所有参数(自变量)在Python里都是按引用传递。

def str_ch(s):
    print id(s)

a = 1
print id(a) # 140397623928280
str_ch(a) # 140397623928280

通过 id 可以看出是引用传递。

但是对于不可变类型,不可变类型的自身是不会被改变的。

def str_ch(s):
    s = s + 1
    print id(s)


a = 1
print id(a) # 140425607286152
str_ch(a) # 140425607286128

num 类型的 a 的内存地址已经改变(或者说a已经是一个新的对象了)

引起 a 改变的操作是 += 操作,原因是 Number 是不可变类型。

不可变类型:int、float、decimal、bool、string、tuple、complex、range、bytes、frozenset

而对于可变类型:

def str_ch(s):
    s.append(2)
    print id(s)


a = [1]
print id(a) # 4359058208
str_ch(a) # 4359058208

list 类型的 b 的内存地址没有发生改变,append()没有产生新对象。

Python 的函数是怎么传递参数的? - FreezeJ的回答 - 知乎 https://www.zhihu.com/question/20591688/answer/139391292
Python 的函数是怎么传递参数的? - resolvewang的回答 - 知乎 https://www.zhihu.com/question/20591688/answer/423314919

Table of Content

Site by Cellophane using Hexo & Random

Hide