问题描述
嘿伙计们,当有人将参数传递给函数时,有人会介意给我一个简单的介绍如何引用Python的工作吗?下面的
代码应该突出我特定的困惑:
< code>
bool1 = True
lst1 = [1,2,3]
def func1(arg1):arg1.append(4)
def func2(arg1):arg1 = False
Hey guys, would someone mind giving me a quick rundown of how
references work in Python when passing arguments into functions? The
code below should highlight my specific confusion:
<code>
bool1=True
lst1=[1,2,3]
def func1(arg1): arg1.append(4)
def func2(arg1): arg1=False
True
< / code>
为什么我的列表变量会在程序的其余部分被更改,但
我的布尔变量不会。我不理解什么?
-
Gregory Pi?ero
首席创新官
混合技术
()
推荐答案
在Python中,x = y具有非常明确的含义y被分配给
名称的x。这个改变不会影响x中的任何内容,因为它开始
,它肯定不会影响其他任何对前面称为x的对象持有
的引用。
在列表上,或者由lst [index] = something赋值)实际上改变了
对象本身,这当然反映在所有其他名称中,这些名称包含
a对象的引用。
In Python, "x = y" has a very definite meaning of "y is assigned to the
name of x." This change does not affect whatever was in x to start
with, and it certainly would not affect anything else which holds a
reference to the object formerly known as x.
In contrast, calling a function which mutates the object (like .append
on lists, or assignment by lst[index]=something) actually changes the
object itself, which is of course reflected by all other names that hold
a reference to the object.
布尔值是不可变的,列表是可变的。你改变(变异)相同的
列表,但是你引用了一个不同的(不可变的)Bool
在Python中,x = y具有非常明确的含义y被分配给x的名称。
Booleans are immutable, lists are mutable. You change (mutate) the same
list, but you are referencing a different (immutable) Bool
In Python, "x = y" has a very definite meaning of "y is assigned to the
name of x."
将其更改为y引用的对象是分配给x",
的名称,你更接近真相。
Change it to "the object referenced by y is assigned to the name of x",
and you''re closer to the truth.
这篇关于将参数传递给函数 - (基本原理令我困惑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!