Python的布尔值是按值传递的吗? [英] Are Python's bools passed by value?

查看:64
本文介绍了Python的布尔值是按值传递的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发送了对bool对象的引用,并在方法中对其进行了修改.方法执行完后,方法外的布尔值保持不变.

I sent a reference to a bool object, and I modified it within a method. After the method finished it's execution, the value of the bool outside the method was unchanged.

这使我相信Python的布尔值是按值传递的.真的吗?还有哪些其他Python类型具有这种行为?

This leads me to believe that Python's bools are passed by value. Is that true? What other Python types behave that way?

推荐答案

Python变量不是C ++的引用".相反,它们只是绑定到对象在内存中任意位置的本地名称.如果该对象本身是可变的,则对该对象的更改将在已将名称绑定到该对象的其他范围中可见.许多原始类型(包括 bool int str tuple )都是不可变的但是.您无法就地更改其价值;而是在您的本地范围内为相同的名称分配一个新值.

Python variables are not "references" in the C++ sense. Rather, they are simply local names bound to an object at some arbitrary location in memory. If that object is itself mutable, changes to it will be visible in other scopes that have bound a name to the object. Many primitive types (including bool, int, str, and tuple) are immutable however. You cannot change their value in-place; rather, you assign a new value to the same name in your local scope.

事实上,几乎在任何时候*,您都会看到格式为 foo = X 的代码,这意味着名称 foo 被分配了一个新值(X ),而不是用 foo 命名的内存中的某个位置正在更新其内部指针,以引用 X 的位置.

In fact, almost any time* you see code of the form foo = X, it means that the name foo is being assigned a new value (X) within your current local namespace, not that a location in memory named by foo is having its internal pointer updated to refer instead to the location of X.

*-Python中唯一的例外是属性的setter方法,该方法可以允许您编写 obj.foo = X 并将其在后台重写以代替调用<代码> obj.setFoo(X).

*- the only exception to this in Python is setter methods for properties, which may allow you to write obj.foo = X and have it rewritten in the background to instead call a method like obj.setFoo(X).

这篇关于Python的布尔值是按值传递的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆