什么是Python中的对象引用? [英] What is an object reference in Python?

查看:84
本文介绍了什么是Python中的对象引用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一本介绍性的Python教科书如下定义了对象引用",但我不明白:

A introductory Python textbook defined 'object reference' as follows, but I didn't understand:

对象引用不过是对象身份(存储对象的内存地址)的具体表示.

An object reference is nothing more than a concrete representation of the object’s identity (the memory address where the object is stored).

教科书试图通过使用箭头将对象引用显示为赋值语句a = 1234中从变量a到对象1234的某种关系来说明这一点.

The textbook tried illustrating this by using an arrow to show an object reference as some sort of relation going from a variable a to an object 1234 in the assignment statement a = 1234.

从我从维基百科((对象)参考)中收集的信息中a = 1234的值将是a1234之间的关联,如果a是指向" 1234(可以随意澄清引用与指针"),但是很难验证就像(1)我正在自学Python,(2)许多搜索结果都在谈论 Java 的引用,以及(3)很少有搜索结果是关于 object 引用的.

From what I gathered off of Wikipedia, the (object) reference of a = 1234 would be an association between a and 1234 were a was "pointing" to 1234 (feel free to clarify "reference vs. pointer"), but it has been a bit difficult to verify as (1) I'm teaching myself Python, (2) many search results talk about references for Java, and (3) not many search results are about object references.

那么,Python中的对象引用是什么?感谢您的帮助!

So, what is an object reference in Python? Thanks for the help!

推荐答案

对象是事物.通常,它们就是您在等式右侧看到的.

Objects are things. Generally, they're what you see on the right hand side of an equation.

可变的名称(通常称为名称")是对实际对象的引用.当名称在方程式 1 的右侧时,将自动查找其引用的对象并将其用于方程式中.右侧表达式的结果是一个对象.等式左侧的名称成为对此(可能是新的)对象的引用.

Variable names (often just called "names") are references to the actual object. When a name is on the right hand side of an equation1, the object that it references is automatically looked up and used in the equation. The result of the expression on the right hand side is an object. The name on the left hand side of the equation becomes a reference to this (possibly new) object.

请注意,如果您正在使用容器对象(例如列表或字典),则可以使用不是显式名称的对象引用:

Note, you can have object references that aren't explicit names if you are working with container objects (like lists or dictionaries):

a = []  # the name a is a reference to a list.
a.append(12345)  # the container list holds a reference to an integer object

以类似的方式,多个名称可以引用相同的对象:

In a similar way, multiple names can refer to the same object:

a = []
b = a

通过查看abid并注意它们是相同的,可以证明它们是同一对象.或者,我们可以查看使ab所引用的对象发生变异的副作用"(如果我们对一个对象进行变异,则因为它们都引用了相同的对象而对两者进行变异).

We can demonstrate that they are the same object by looking at the id of a and b and noting that they are the same. Or, we can look at the "side-effects" of mutating the object referenced by a or b (if we mutate one, we mutate both because they reference the same object).

a.append(1)
print a, b  # look mom, both are [1]!

1 更准确地说,是在表达式中使用名称时

1More accurately, when a name is used in an expression

这篇关于什么是Python中的对象引用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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