编程语言
首页 > 编程语言> > Python设计模式和pickle模块

Python设计模式和pickle模块

作者:互联网

设计模式

在IT行业中设计模式总共有23种,可以分为三大类,创建型,结构型,行为型。

设计模式之单例模式。

单例模式的意思是一个类只能产生一个对象,用于节省资源。

第一种(基于classmethod)

class Mysql(object):
    _instance = None

    def __init__(self, ip, port):
        self.ip = ip
        self.port = port

    @classmethod
    def singleton(cls):
        if not cls._instance:
            cls._instance = Mysql('127.0.0.1', 3306)
        return cls._instance


obj1 = Mysql.singleton()
obj2 = Mysql.singleton()
print(obj1)
print(obj2)

第二种(基于装饰器)

def singleton(cls):
    # 该对象在类Mysql被装饰上singleton的时候就已经实例化完毕
    _instance = cls('127.0.0.1',3306)
    def inner(*args,**kwargs):
        # 判断是否传入参数,传入参数表示要实例化新的,不传表示用默认的
        if args or kwargs:
            obj = cls(*args,**kwargs)
            return obj
        return _instance
    return inner

@singleton
class Mysql:
    def __init__(self,ip,port):
        self.ip = ip
        self.port = port

obj1 = Mysql()
obj2 = Mysql()
obj3 = Mysql()
print(obj1,obj2,obj3)

第三种(基于元类)

class MymetaClass(type):
    def __call__(self, *args, **kwargs):
        if not hasattr(self,'instance'):
            self.instance = super().__call__(*args,**kwargs)
        return self.instance

class Mysql(metaclass=MymetaClass):
    def __init__(self,host,port):
        self.host = host
        self.port = port
obj = Mysql('ajdak',213)
obj1 = Mysql('asdasdas',134234)
print(obj,obj1)

第四种(基于__new__)

class Mysql(object):
    _instance = None
    def __init__(self,name):
        self.name = name

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = object.__new__(cls)
        return cls._instance

obj = Mysql('egon')
obj1 = Mysql('jason')
print(id(obj),id(obj1))

第五种(基于模块)

# 单独在一个py文件中定义一个类,并实例化一个对象,之后在其他文件导入这一对象,实现单例
class Singleton(object):
    def __init__(self,host,port):
        self.host = host
        self.port = port

singleton = Singleton('127.0.0.1',3306)

pickle模块

将该模块的目的仅仅是为了在选课系统中使用,后期会学习ORM就不会用pickle了。并且该模块只支持python 兼容性很差!!!

将对象保存到文件`

import pickle

class MyClass(object):
    school = 'school'
    def __init__(self, name):
        self.name = name
    def choose_course(self):
        print('%s正在选课'%self.name)
obj = MyClass('jason')
print(obj.school)
obj.choose_course()

从文件中获取对象

with open(r'jason','rb') as f:
    data = pickle.load(f)
print(data)
print(data.name)
print(data.school)

标签:__,Python,self,instance,Mysql,设计模式,pickle,port,cls
来源: https://www.cnblogs.com/zaoan1207/p/16138351.html