Python_面向对象_单例模式
class A(object): pass a1 = A() a2 = A()
print(a1 == a2)
print(id(a1))
print(id(a2))
结果:
1 False 2 2325723198184 3 2325723198464
a1与a2的内存地址不同,a1与a2是不一样的.
1 class A(object): 2 3 def __init__(self): 4 self.y=10 5 self.x=44 6 x=10 7 y=12 8 9 10 class B(A): 11 12 x=8 13 y=20 14 15 b=B() 16 print(b.y) 17 print(b.x)
结果:
1 10 2 44
程序执行过程:
先找def的值,然后找class中其他的,找不到再去父类中去找,知道后就停止向上级查找,输出结果.
单例模式:
1 class Settings(object): 2 _instance = None 3 4 def __new__(cls, *args, *kw): 5 if not cls._instance: 6 cls._instance = super(Settings, cls).__new__(cls, *agrs, **kw) 7 return cls._instance 8 9 s1 = Settings() 10 s2 = Settings() 11 12 print(s1 == s2) 13 print(id(s1)) 14 print(id(s2))
结果:
1 True 2 1705906981800 3 1705906981800
小彩蛋:
1 print(1<2==2) 2 print(1 < 2 and 2 == 2)
结果:
1 True 2 True
按照该官方文档解释,
”5== len(a)== len(b)“等价于”5== len(a) and len(a)==len(b)“
以此类推,得到上述结果.