|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import copy # 引入 copy 模块
class aa:
s2 = None
def __init__(self):
self.s1 = None
self.s2 = None
def asa(self,bb):
self.s1 = bb
aa.s2 = self.s1 # 用深拷贝
return aa.s2
#return self.s2
def sadsa(self):
self.s1.id = 3
class bb:
def __init__(self):
self.id = 0
def setId(self,id):
self.id = id
c = bb()
c.setId(2)
#print(c.id)
d = aa()
d.asa(c)
d.sadsa()
print(d.s2.id)
#print(d.asa(c).id)
#print(c.id)
把s2从实例变量改成类变量后为什么会报错呢?
因为实例变量把类变量给覆盖掉了
import copy
class aa:
s2 = None
def __init__(self):
self.s1 = None
self.s2 = None
def asa(self,bb):
self.s1 = bb
aa.s2 = self.s1
return aa.s2
#return self.s2
def sadsa(self):
self.s1.id = 3
class bb:
def __init__(self):
self.id = 0
def setId(self,id):
self.id = id
c = bb()
c.setId(2)
#print(c.id)
d = aa()
d.asa(c)
d.sadsa()
print(aa.s2.id) # 这里把 d 改成 aa 不会报错
#print(d.asa(c).id)
#print(c.id)
import copy
class aa:
s2 = None
def __init__(self):
self.s1 = None
self.s2 = None # 这里初始化了实例变量,就是这个把类变量给覆盖了
def asa(self,bb):
self.s1 = bb
aa.s2 = self.s1
del self.s2 # 删掉实例变量
return aa.s2
#return self.s2
def sadsa(self):
self.s1.id = 3
class bb:
def __init__(self):
self.id = 0
def setId(self,id):
self.id = id
c = bb()
c.setId(2)
#print(c.id)
d = aa()
d.asa(c)
d.sadsa()
print(d.s2.id)
#print(d.asa(c).id)
#print(c.id)
|
|