#python中單例模式
#1.使用__new__ class Singleton: def __new__(cls,*args,**kwargs): if not hasattr(cls,'_instance'): cls._instance=super().__new__(cls) return cls._instance s0=Singleton() s1=Singleton() print(id(s0)) print(id(s1))
In [10]:
#hasattr(object,name)函數用於判斷是否包含對應的屬性
#參數: object------對象 name------字符串,屬性名 #返回值: 如果對象有該屬性返回True,否則返回False class People: country="china" def __init__(self,name): self.name=name def people_info(self): print("%s is xxx"%(self.name)) obj=People('aaa') print(obj.name) print(hasattr(People,'country')) print(hasattr(obj,'name')) print(hasattr(People,'name')) print(hasattr(People,'people_info')) print(hasattr(obj,'people_info')) print(People.__dict__) print(obj.__dict__)
In [14]:
#2.使用裝飾器
from functools import wraps def singlenton(cls): instances={} @wraps(cls) def getinstance(*args,**kwargs): if cls not in instances: instances[cls]=cls(*args,**kwargs) return instances return getinstance @singlenton class Bar: pass b0=Bar() b1=Bar() print(id(b0)) print(id(b1))
裝飾器的用法(小應用)
def outer(func): def inner(): print("before func") ret=func() return ret+1 return inner #返回inner函數
@outer #解釋器執行 foo=outer(foo) def foo(): return 1
print(foo) foo()
這個過程中執行了下面幾步
1.函數 foo 作為 裝飾器 outer 的參數被傳入 2.函數 inner 對 func 進行調用,然后裝飾器 outer 返回 inner 3.原來的函數名 foo 關聯到 inner,如上面的foo 所示,調用 foo時間上是在調用 inner
In [ ]:
#裝飾器的應用小例子
#將對象作為函數的參數,去判斷對象參數 def wrapper(func): def checker(a,b): if a.x<0 or a.y <0: a=Coordinate(a.x if a.x>0 else 0,a.y if a.y>0 else 0) if b.x<0 or b.y<0: b=Coordinate(b.x if b.x>0 else 0,b.y if b.y>0 else 0) ret=func(a,b) if ret.x<0 or ret.y<0: ret = Coordinate(ret.x if ret.x>0 else 0,re.y if ret.y>0 else 0) return ret return checker class Coordinate(object): def __init__(self,x,y): self.x=x self.y=y def __repr__(self): return "Coord:"+str(self.__dict__) @wrapper def add(a,b): return Coordinate(a.x+b.x,a.y+b.y) @wrapper def sub(a,b): return Coordinate(a.x-b.x,a.y-b.y) one=