使用模块
其实,**Python 的模块就是天然的单例模式**,因为模块在第一次导入时,会生成 `.pyc` 文件,当第二次导入时,就会直接加载 `.pyc` 文件,而不会再次执行模块代码。
因此,我们只需把相关的函数和数据定义在一个模块中,就可以获得一个单例对象了。如果我们真的想要一个单例类,可以考虑这样做:
mysingleton.py
class Singleton(object): def foo(self): pass singleton = Singleton()
将上面的代码保存在文件 mysingleton.py
中,要使用时,直接在其他文件中导入此文件中的对象,这个对象即是单例模式的对象
from a import singleton
使用装饰
def Singleton(cls): instance = None def _singleton(*args, **kargs): nonlocal instance if not instance: instance = cls(*args, **kargs) return instance return _singleton @Singleton class A(object): def __init__(self, x=0): self.x = x a1 = A(2) a2 = A(3) print(a1.x) print(a2.x) print(a1 is a2)
适用类方法
class Singleton(object): _instance=None def __init__(self): pass @classmethod def instance(cls, *args, **kwargs): if not cls._instance: cls._instance=cls(*args, **kwargs) return cls._instance a1=Singleton.instance() a2=Singleton().instance() print(a1 is a2)
基于new方法实现
class Singleton(object): _instance=None def __init__(self): pass def __new__(cls, *args, **kwargs): if not cls._instance: cls._instance = object.__new__(cls) return cls._instance obj1 = Singleton() obj2 = Singleton() print(obj1 is obj2)
基于metclass方式实现
class SingletonType(type): _instance=None def __call__(cls, *args, **kwargs): if not cls._instance: # cls._instance = super().__call__(*args, **kwargs) cls._instance = object.__new__(cls) cls._instance.__init__(*args, **kwargs) return cls._instance class Foo(metaclass=SingletonType): def __init__(self,name): self.name = name obj1 = Foo('name') obj2 = Foo('name') print(obj1.name) print(obj1 is obj2)
补充问题
from django.contrib import admin from django.urls import path, include from home import views # pycharm报错,但实际上不报错 ,只需要把加入到环境变量的路径都做成source root即可 from django.views.static import serve from django.conf import settings import os from django.shortcuts import HttpResponse class Foo(): url = 'http://www.baidu.com' def demo(self,request): # self 就不是Foo的对象了,它是request对象 print(type(self)) # django.core.handlers.wsgi.WSGIRequest print(self.url) # 'WSGIRequest' object has no attribute 'url' return HttpResponse('sdfa') urlpatterns = [ path('demo/', Foo().demo), # Foo.demo(request) ]
标签:__,self,模式,instance,单例,._,def,cls From: https://www.cnblogs.com/shanghaipudong/p/17772890.html