def foo(**args):
for k, v in args.items():
print type(k), type(v)
for k, v in args.items():
k = v
print k
p开发者_Python百科rint type(k)
foo(a = 10)
foo(**{'a':10})
Gives me
<type 'str'> <type 'int'>
10
<type 'int'>
<type 'str'> <type 'int'>
10
<type 'int'>
So I am confused how am I able to do this as k is a string, so shouldn't I not be able to assign to it?
I obviously can't do
In [35]: 'a' = 10
------------------------------------------------------------
File "<ipython console>", line 1
SyntaxError: can't assign to literal (<ipython console>, line 1)
k
is not a string, it is the name of a variable. You can easily do
k = 'a'
k = 10
without any problem, since an assignment statement in Python will assign the name to point to whichever value is on the right-hand side.
Strings are immutable, as you mentioned, but this means that as an object, it has no method you can call that will cause it to modify its data. Every variable in Python can always be assigned to point to something else.
For example, if you say
x = y = 'hello'
then both x
and y
refer to the same object, but assignment statements like
x += 'world'
or
x = 'bacon'
will change the binding of x
to point to something else.
k is not a string, it is just a loop variable. You've just assigned some new value to it and it lost its relation to the dictionary you are iterating over.
Well, when you do for k, v in args.items()
, in the first (and the only, in your case) iteration the identifier k
starts pointing to a current key of the dictionary "args", which happens to be a string, right?
When you do k = v
, k
starts pointing to whatever v
points to, which just happens to be an integer. I don't see much of a problem here.
If I understand it correctly, the values of variables in python are references to objects.
精彩评论