类变量和实例变量的区别
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)
页:
[1]