Python3中的单例模式 hasattr() getattr() serattr() delattr()

Python3中的单例模式 hasattr() getattr() serattr() delattr()

#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__) 
 
aaa
True
True
False
True
True
{'__module__': '__main__', 'country': 'china', '__init__': <function People.__init__ at 0x0000024A642A7A60>, 'people_info': <function People.people_info at 0x0000024A642A78C8>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
{'name': 'aaa'}
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)) 
 
2518531933456
2518531933456
 

装饰器的用法(小应用)

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值