Python:发生不必要的变量更改 [英] Python: unwanted change of variable occurs

查看:71
本文介绍了Python:发生不必要的变量更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
最少惊讶"在Python中:可变默认参数

Possible Duplicate:
“Least Astonishment” in Python: The Mutable Default Argument

好的,所以基本上我有以下代码:

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]中,而不是简单地分配它,以便它们使用两个不同的内存地址来存储其值(请参见

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:发生不必要的变量更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆