#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=