2个相同类的独立python对象具有相同的属性和相同的地址

时间:2019-01-03 21:40:55

标签: python

当我创建2个对象时,即使它们是独立声明的,它们也具有相同的属性(示例中称为mem的列表),并且具有相同的地址。 如果我在obj1的列表中添加一个元素(称为mem),则obj2将具有具有相同地址的相同属性mem。

代码

class Test:
    def __init__(self, init_mem=[]):
        self.mem = init_mem
    def add(self,s):
        self.mem.append(s)

obj1 = Test()
obj1.add(1)
obj2 = Test()
print("obj1.mem", obj1.mem)
print("obj2.mem", obj2.mem)

print("address obj1", hex(id(obj1)))
print("address obj2", hex(id(obj2)))

print("address obj1.mem", hex(id(obj1.mem)))
print("address obj2.mem", hex(id(obj2.mem)))

结果:

test.mem [1]
test2.mem [1]
address obj1 0x7f170e6ae1d0
address obj2 0x7f170ccb8278
address obj1.mem 0x7f170ccc5148
address obj2.mem 0x7f170ccc5148

似乎当我声明第二个对象obj2时,默认值init_mem = []实际上是obj1.mem,而不是一个空列表。

如果我指定初始值init_mem = [],则具有预期的行为

obj1 = Test([])
obj1.add(1)
obj2 = Test()
print("obj1.mem", obj1.mem)
print("obj2.mem", obj2.mem)

print("address obj1", hex(id(obj1)))
print("address obj2", hex(id(obj2)))

print("address obj1.mem", hex(id(obj1.mem)))
print("address obj2.mem", hex(id(obj2.mem)))

结果

obj1.mem [1]
obj2.mem []
address obj1 0x7f79aa7201d0
address obj2 0x7f79a8d2a278
address obj1.mem 0x7f79a8d38308
address obj2.mem 0x7f79a8d38148

0 个答案:

没有答案