简体   繁体   中英

what's the difference between assign and bound when talking about variable?

Except from http://www.stavros.io/tutorials/python/

# This swaps the variables in one line(!).
# It doesn't violate strong typing because values aren't
# actually being assigned, but new objects are bound to
# the old names.
>>> myvar, mystring = mystring, myvar

I don't understand the point he is making.

He means to say the two variables are essentially swapped without knowing their types or explicitly using an intermediate variable as you normally would. A weakly-typed swap looks like this:

temp = A
A = B
B = temp

A previously-unitialized temporary variable temp must be created in order to perform the swap. However, because no type is specified when temp is first created, it violates strong typing. Here is a strongly-typed swap:

int temp = A
A = B
B = temp

A swap like A, B = B, A does not violate strong typing because an intermediate variable doesn't need to be explicitly defined with or without a type. It's simply an assignment operation, and a basic assignment operation is always ambiguously typed (aka: A = B is the same regardless of whether you are using a strong-typed language or a weak-typed one).

An assignment like a=1 , conceptually Python will perform three distinct steps to carry out the request.

1.Create an object to represent the value 1

2.Create the variable a .

3.Link(or bound as in the link) the variable a to new object 1 .

In your case, the statement

myvar, mystring = mystring, myvar

will change the variable-object bound relationship.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM