问题
In x = 1
, are both x
and 1
objects? Because print(1)
and x = 1; print(x)
will result in the same output.
Even the syntax of print
function is:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
回答1:
Names in Python are not objects. Using a name in an expression automatically evaluates to the object referred to by the name. It is not possible to interact with the name itself in any way, such as passing it around or calling a method on it.
>>> x = 1
>>> type(1) # pass number to function...
<class 'int'> # ...and receive the number!
>>> type(x) # pass name to function...
<class 'int'> # ...but receive the target!
Note that technically, 1
is also not an object but a literal of an object. Only the object can be passed around – it does not reveal whether it originates from a literal 1
or, for example, a mathematical expression such as 2 - 1
.
回答2:
1
is an int
object. x
is a variable which has a reference to the object.
For more in depth on pass-by-reference vs pass-by-value see this answer. It says:
The variable is not the object.
print()
will output the representation of the object, which 1
and x
both point to.
What is interesting in this case is that you could create multiple instances of identical objects by simply creating more variables that have the same value, but point to different instances. For example:
x = 1000
y = 1000
z = 1000
These are 3 different objects which are equal to each other, but still separate objects.
For numbers from -5 to 255, the python interpreter will cache the object instances so that all Integers in that range only have one instance. If the above example were 1 instead of 1000, x
,y
, and z
would actually point to the same object.
来源:https://stackoverflow.com/questions/62433210/in-x-1-are-both-x-and-1-objects