问题描述
好的,所以基本上我有以下代码:
Okay, so basically I have this code:
# Our Rule type.
class Rule(object):
"""An object to represent a rule and include
methods to apply these rules."""
def __init__(self,bind="F",rule=["F"]):
self.bind = bind
self.rule = rule
def show(self):
try:
print self.bind
#print self.rule
for i in range(len(self.rule)):
print self.rule[i]
except:
print "Incomplete"
def inflate(self,seq):
for i in range(len(seq)):
if seq[i] == self.bind:
seq[i] = self.rule
elif type(seq) == type(["X"]):
seq[i] = self.inflate(seq[i])
return seq
def inflate_depth(self,seq,depth):
while depth > 0:
seq = self.inflate(seq)
depth = depth - 1
print self.rule
return seq
我使用以下代码从另一个文件中调用它:
I call it from another file with this code:
pity = Rule(rule=["R","F","L","F","L","F","R","F"])
seq = ["F"]
inf = pity.inflate_depth(seq,2)
所以,我应该得到一个看起来像这样的列表:
So, I should end up with a list that looks like this:
[['R', [...], 'L', [...], 'L', [...], 'R', [...]]]
似乎可以正常工作,但是有一个基本错误.
Which seems to work fine, but there is one fundamental error.
self.rule
已被更改为包含['R', [...], 'L', [...], 'L', [...], 'R', [...]]
为什么?无论如何,我都没有为该变量分配新值,但是它仍然会更改.
Why? There is no where whatsoever I assign a new value to that variable, but it changes nonetheless.
推荐答案
对此我不确定100%,但是我怀疑问题是Python中的变量是引用而不是值.也就是说,设置seq[i] = self.rule
时,seq[i]
指向self.rule
在内存中的存储位置,对seq[i]
的值所做的任何更改都会导致对self.rule
的更改,因为它们的值存储在内存中的相同位置.
I'm not 100% sure about this but I suspect the problem is that variables in Python are references and not values. That is to say, when you set seq[i] = self.rule
, seq[i]
points to where self.rule
is stored in memory and any changes made to seq[i]
's value results in a change to self.rule
since their values are stored at the same location in memory.
您可能应该做的是将self.rule
的值深度复制到seq[i]
中,而不是简单地分配它,以便它们使用两个不同的内存地址来存储其值(请参见 http://docs.python.org/library/copy.html 了解更多信息),这样分配给seq[i]
的方法将不会会影响self.rule
.
What you probably should do is deep copy self.rule
's value into seq[i]
rather than simply assign it so that they use two different memory addresses to store their values (see http://docs.python.org/library/copy.html for more information), that way assigning to seq[i]
won't affect self.rule
.
这篇关于Python:发生不必要的变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!