我对 python 有一个小问题。我找到了一种绕过它的方法,但它仍然困扰着我......以下面的代码为例,我试图将问题重写为最简单的形式:
"WE DEFINE A SIMPLE OBJET"
class Object():
def __init__(self,argument):
self.table = argument
"We define an array that will be used as the argument for the 'Object' instances"
tab = [0,0]
"We instanciate 2 'Object' using the 'tab' array as an argument"
Obj1=Object(tab)
Obj2=Object(tab)
"We change the first value of the first Object's table to 1"
Obj1.table[0] = 1
"RESULTS (we are expecting the first Object's tab to be [1,0] and the second to be [0,0] but we get [1,0] for both)"
print(Obj1.table)
print(Obj2.table)
出去 :
>>[1,0]
>>[1,0]
这似乎是,代替创建对象self.table用“可变标签”值,则self.table链接到标签通过它的参考变量。结果,当我们尝试修改两个对象之一中的self.table变量时,它也会在所有其他实例中被修改。正常吗?我的代码有问题吗?
有关信息,我通过将第 4 行更改为:
self.table = [argument[x] for x in range(len(argument))]
谢谢!!:)
PS:我不知道是否有任何链接,但这种其他行为也困扰着我。也许根本原因是一样的:
在 :
a = [[0,0]]*2
a[0][0] = 1
print(a)
出去 :
>> [[1, 0], [1, 0]]
这是一个意想不到的结果,而,
在 :
a = [[0,0] for x in range(2)]
a[0][0] = 1
print(a)
出去 :
>> [[1, 0], [0, 0]]
给出了预期的结果.. :p
临摹微笑
Smart猫小萌
相关分类