标签:paint lis end sel def Painter str 办公 return
例子为办公室人员共用同一台打印机的模式
class Manager:
# 使用打印机上传要打印的信息
def use_painter(self, info, pr):
pr.add_task(info)
class Staff:
# 使用打印机上传要打印的信息
def use_painter(self, info, pr):
pr.add_task(info)
class Potiner:
#创建一个打印机类,并用两个类变量来控制 __new__和__init__方法
__stance = None
__is_init = False
重写一个__new__方法,并创建一个单类模式
def __new__(cls, *args, **kwargs):
if cls.__stance is None:
cls.__stance = object.__new__(cls)
return cls.__stance
#让程序调用时只初始化一次self.get_list
def __init__(self):
print("1111111")
if Potiner.__is_init is False:
print("-----------")
self.get_list = []
Potiner.__is_init = True
#打印方法
def add_task(self, info):
# Potiner.list_print(info)
self.get_list.append(info)
#打印数据
def get_print(self):
print(self.get_list)
# A员工
pr1 = Potiner()
m1 = Manager()
m1.use_painter("hello", pr1)
# B员工
pr2 = Potiner()
str1 = Staff()
str1.use_painter("python", pr2)
# C员工
pr = Potiner()
pr.get_print()
print(id(pr1))
print(id(pr2))
print(id(pr))
标签:paint lis end sel def Painter str 办公 return
原文地址:https://www.cnblogs.com/wangxiongbing/p/9901733.html