问题描述:一个类(Test1)的实例(test1)作为参数传入到另一个类(Test2)中,Test2中修改了test1中某个变量的值,那么test1中该变量是否发生改变?
解答:
class Test1():
def __getitem__(self, key):
return getattr(self, key)
def __setitem__(self, key, val):
setattr(self, key, val)
a = 1
test1 = Test1()
class Test2():
def __init__(self,params):
self.params = params
self.params['a']=2
test2 =Test2(test1)
print(test1['a'],test2.params['a'])
print(id(test1['a']),id(test2.params['a'])) # 检查地址是否相同
输出为:
2 2
140717250093488 140717250093488