首页 > 其他分享 >单列模式与pickle模块

单列模式与pickle模块

时间:2022-11-09 18:04:02浏览次数:44  
标签:__ .__ name 单列 模块 Mysql pickle self def

单列模式实现的多种方法

单列模式实现的多种方法方式

class C1:
    __instance = None

    def __init__(self, name, age):
        self.name = name
        self.age = age

    @classmethod
    def singleton(cls):
        if not cls.__instance:
            cls.__instance = cls('jason', 18)
        return cls.__instance


obj1 = C1.singleton()
obj2 = C1.singleton()
obj3 = C1.singleton()
print =(id(obj1),id(obj2),id(obj3))
obj4 = C1('kevin',28)
obj5 = C1('tony',39)
print(id.(obj4),id(obj5)

class Mymeta(type):
    def __init__(self, name, bases, dic):  # 定义类Mysql时就触发
        # 事先先从配置文件中取配置来造一个Mysql的实例出来
        self.__instance = object.__new__(self)  # 产生对象
        self.__init__(self.__instance, 'jason', 18)  # 初始化对象
        # 上述两步可以合成下面一步
        # self.__instance=super().__call__(*args,**kwargs)
        super().__init__(name, bases, dic)

    def __call__(self, *args, **kwargs):  # Mysql(...)时触发
        if args or kwargs:  # args或kwargs内有值
            obj = object.__new__(self)
            self.__init__(obj, *args, **kwargs)
            return obj
        return self.__instance


class Mysql(metaclass=Mymeta):
    def __init__(self, name, age):
        self.name = name
        self.age = age

obj1 = Mysql()
obj2 = Mysql()
print(id(obj1), id(obj2))
obj3 = Mysql('tony', 321)
obj4 = Mysql('kevin', 222)
print(id(obj3), id(obj4))
'''基于模块的单例模式:提前产生一个对象 之后导模块使用'''
class C1:
    def __init__(self, name):
        self.name = name

obj = C1('jason')


def outer(cls):
    _instance = cls('jason', 18)
    def inner(*args, **kwargs):
        if args or kwargs:
            obj = cls(*args, **kwargs)
            return obj
        return _instance

    return inner


@outer  # Mysql=outer(Mysql)
class Mysql:
    def __init__(self, host, port):
        self.host = host
        self.port = port


obj1 = Mysql()
obj2 = Mysql()
obj3 = Mysql()
print(obj1 is obj2 is obj3)  # True

obj4 = Mysql('1.1.1.3', 3307)
obj5 = Mysql('1.1.1.4', 3308)
print(obj3 is obj4)  # False

pickle序列化模块

优势:能够序列化python中所有的类型
缺陷:只能够在python中使用,无法跨语言传输


需求:产生一个对象并保存到文件中,取出来还是一个对象

class Myclass:
    def __init__(self, name):
        self.name = name

    def choice_course(self):
        print(f'{self.name}正在选课')


obj = Myclass('jason')
# print(obj)  # <__main__.Myclass object at 0x000001F5032B3B50>
# obj.choice_course()  # jason正在选课

import pickle

"""pickle序列化把对象保存到文件中"""
with open(r'a.txt', 'wb') as f:
    pickle.dump(obj, f)
"""pickle反序列化从文件中取出对象"""
with open(r'a.txt', 'rb') as f:
    data = pickle.load(f)
    
print(data)  # <__main__.Myclass object at 0x0000012502804BB0>
data.choice_course()  # jason正在选课


标签:__,.__,name,单列,模块,Mysql,pickle,self,def
From: https://www.cnblogs.com/lvqingmei/p/16874674.html

相关文章