gpt4 book ai didi

Python:发生不需要的变量更改

转载 作者:行者123 更新时间:2023-11-28 20:52:01 24 4
gpt4 key购买 nike

<分区>

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

好的,基本上我有这段代码:

 # 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

我用这段代码从另一个文件调用它:

pity = Rule(rule=["R","F","L","F","L","F","R","F"])

seq = ["F"]

inf = pity.inflate_depth(seq,2)

所以,我应该得到一个如下所示的列表:

[['R', [...], 'L', [...], 'L', [...], 'R', [...]]]

这似乎工作正常,但存在一个根本性错误。

self.rule

已更改为包含 ['R', [...], 'L', [...], 'L', [...], 'R', [... ]]

为什么?我没有为该变量分配新值,但它仍然发生了变化。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com