__new__
原理
python的模块就是天然的单例模式,因为模块在第一次导入时,会生成.pyc文件,当第二次导入时,就会直接加载.pyc文件,而不会再次执行模块代码。因此我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了
银行卡类(card.py)
class BankCard(object):
def __init__(self, cardId, passwd, money):
self.cardId = cardId
self.passwd = passwd
self.money = money
card = BankCard("888888", "888888", 1000)
丈夫类(husband.py)
from bankCard import card
class Husband(object):
def play(self):
print(card.money)
妻子类(wife.py)
from bankCard import card
class Wife(object):
def face(self):
card.money -= 100
主文件(main.py)
from wife import Wife
from husband import Husband
def main():
w = Wife()
h = Husband()
w.face()
h.play()
if __name__ == "__main__":
main()
__new__
实现单例银行卡类(card.py)
class BankCard(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, "instance"):
# 调用父类中的__new__()得到混沌对象
cls.instance = super().__new__(cls)
return cls.instance
def __init__(self):
self.cardId = "88888888"
self.passwd = "88888888"
丈夫类(husband.py)
from bankCard import BankCard
class Husband(object):
def play(self):
card = BankCard()
print(card.money)
妻子类(wife.py)
from bankCard import BankCard
class Wife(object):
def face(self):
card = BankCard()
card.money = 1000
card.money -= 100
主文件(main.py)
from wife import Wife
from husband import Husband
def main():
w = Wife()
h = Husband()
w.face()
h.play()
if __name__ == "__main__":
main()
银行卡类(card.py)
def single(cls):
# Person:obj,A:obj
instance = {}
def inner(*args, **kwargs):
if cls not in instance:
instance[cls] = cls(*args, **kwargs)
return instance[cls]
return inner
@single
class BankCard(object):
def __init__(self):
self.cardId = "88888888"
self.passwd = "88888888"
self.money = 1000
@single
class A(object):
pass
丈夫类(husband.py)
from bankCard import BankCard
class Husband(object):
def play(self):
card = BankCard()
print(card.money)
妻子类(wife.py)
from bankCard import BankCard
class Wife(object):
def face(self):
card = BankCard()
card.money -= 200
主文件(main.py)
from wife import Wife
from husband import Husband
def main():
w = Wife()
h = Husband()
w.face()
h.play()
if __name__ == "__main__":
main()