据我所知,Python中的变量只是指针.
基于此规则,我可以假设此代码段的结果:
i = 5
j = i
j = 3
print(i)
Run Code Online (Sandbox Code Playgroud)
会的3.但是我得到了一个意想不到的结果,是的5.
此外,我的Python书确实涵盖了这个例子:
i = [1,2,3]
j = i
i[0] = 5
print(j)
Run Code Online (Sandbox Code Playgroud)
结果将是[5,2,3].
我理解错了什么?
for在Python中使用循环迭代列表中的项时,是否会更改item(下面)更改相应的项items?
for item in items:
item += 1
Run Code Online (Sandbox Code Playgroud)
项目中的每个项目是否会增加或保持与循环之前相同?
[注意:我对Python 2.7和3.x感兴趣]
cache = {}
def func():
cache['foo'] = 'bar'
print cache['foo']
Run Code Online (Sandbox Code Playgroud)
产量
bar
Run Code Online (Sandbox Code Playgroud)
为什么这样做以及为什么不需要使用global关键字?
我是Python的新手(并且不管怎么说都不太了解),但我记得读过python通常不会复制值,所以任何语句a = b都会使b指向a.如果我跑
a = 1
b = a
a = 2
print(b)
Run Code Online (Sandbox Code Playgroud)
给出结果1.不应该是2吗?
我从考试中得到了下面的代码,我不明白为什么你第一次做f2 = f1,做f1.set()更改f2但是之后你设置时f1 = Foo("Nine", "Ten")根本没有改变f2.如果有人知道为什么请向我解释.非常感谢!
码:
class Foo():
def __init__(self, x=1, y=2, z=3):
self.nums = [x, y, z]
def __str__(self):
return str(self.nums)
def set(self, x):
self.nums = x
f1 = Foo()
f2 = Foo("One", "Two")
f2 = f1
f1.set(["Four", "Five", "Six"])
print f1
print f2
f1 = Foo("Nine", "Ten")
print f1
print f2
f1.set(["Eleven", "Twelve"])
print f1
print f2
Run Code Online (Sandbox Code Playgroud)
结果:
['Four', 'Five', 'Six']
['Four', 'Five', 'Six']
['Nine', 'Ten', 3] …Run Code Online (Sandbox Code Playgroud) 如果我有这个Python代码:
foo = [3, 5, 9]
bar = foo
bar.append(9)
print(foo)
Run Code Online (Sandbox Code Playgroud)
它回来了
[3, 5, 9, 9]
Run Code Online (Sandbox Code Playgroud)
这肯定意味着当我追加9时bar,它也会受到影响foo.如何使变量bar等于foo,但是当我编辑时bar,它不起作用foo?
我有一个存储的字符串列表 wk
我运行以下代码.
n_wk=wk
for i in range(10):
if some condition:
n_wk[i]='new'
Run Code Online (Sandbox Code Playgroud)
我想保留这些wk价值观.但是,wk它也随着变化而变化n_wk.任何人都可以指出这个错误吗?
这两个类定义结构相同,除了在奇怪的()类定义中,属性'd'是一个列表,而在normal()类定义中它是一个int.我不明白为什么奇怪的()类导致self.d = d,而类normal()不是这种情况.为什么Python会在这种情况下对int和列表进行不同的处理?
class weird:
def __init__(self):
d = [1,2,3]
self.d = d
for x in range(3):
d[x] = 10+x
print "d =", d
print "self.d =", self.d
class normal:
def __init__(self):
d = 1
self.d = d
d = 11
print "d =", d
print "self.d =", self.d
Run Code Online (Sandbox Code Playgroud)
当我运行代码时,我得到了
>>> a=weird()
d = [10, 11, 12]
self.d = [10, 11, 12]
>>> b=normal()
d = 11
self.d = 1
Run Code Online (Sandbox Code Playgroud) 只是想知道这个背后的逻辑是什么?从表面上看,似乎效率低下,每当你做一些像"x = x + 1"这样简单的事情时,它必须采用一个新地址并丢弃旧地址.
python ×9
class ×2
list ×2
identifier ×1
mutability ×1
namespaces ×1
pointers ×1
string ×1
variables ×1