"""
单例模式特别像中国的婚姻法:
一夫一妻制
如果需要结婚,必须到民政局登记
民政局 检测两个人的户口本 看上面的结婚状态
已婚 不予登记
未婚 给予登记
那么按照这个思路实现python中的单例模式
1.需要一个方法,可以去控制当前对象的创建过程
__new__
2.需要一个标识来存储和表示是否有对象
创建一个私有属性进行存储,默认值为None
3.在创建对象的方法中去检测和判断是否有对象?
如果没有对象,则创建对象,并把对象存储起来,返回对象
如果存储的是对象,则直接返回对象,就不需要创建新的对象了
"""
from typing import Any
class base():
obj = 1
b = base()
print(b)
b1 = base()
print(b1)
b2 = base()
print(b2)
class Danli_():
obj = 1
def __new__(cls, *args, **kwargs):
return cls
d_ = Danli_()
print(d_)
d1_ = Danli_()
print(d1_)
d2_ = Danli_()
print(d2_)
class Danli():
__obj = None
def __new__(cls, *args, **kwargs):
if not cls.__obj:
cls.__obj = object.__new__(cls)
return cls.__obj
d1 = Danli()
print(d1)
d2 = Danli()
print(d2)
d3 = Danli()
print(d3)
class Car:
instance = None
isCreate = False
def __new__(cls, brand, color, wheel):
if Car.instance == None:
Car.instance = super().__new__(cls)
return Car.instance
def __init__(self, brand, color, wheel):
if Car.isCreate == False:
self.brand = brand
self.color = color
self.wheel = wheel
Car.isCreate = True
def show(self):
print(self.brand, self.color, self.wheel)
c1 = Car("五菱宏光", "粉色", 4)
print(id(c1))
c1.show()
c2 = Car("拖拉机", "黄金色", 4)
c2.show()
print(id(c2))
c3 = Car("路虎", "白色", 4)
print(id(c3))
c3.show()

- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 88
- 89
- 90
- 91
- 92
- 93
- 94
- 95
- 96
- 97
- 98
- 99
- 100
- 101
- 102
- 103
- 104
- 105
- 106
- 107
- 108
- 109
- 110
- 111
- 112
- 113
- 114
- 115
- 116
- 117
- 118
- 119
- 120
- 121
- 122
- 123
- 124
- 125
- 126
- 127