1.__new__方法
class Son(object):
__instance = None
def __new__(cls,*args,**kwargs):
if not cls.__instance:
cls.__instance = object.__new__(cls)
return cls.__instance
a =Son()
b =Son()
print(id(a))
print(id(b))
2.装饰器方法
def pro(class_):
info = {}
def wrappend(*args,**kwargs):
if class_ not in info:
info[class_] = class_(*args,**kwargs)
return info[class_]
return wrappend
@pro
class Foo():
pass
a = Foo()
b = Foo()
print(id(a))
print(id(b))
3.类装饰器方法
class Son(object):
__instance = None
def __init__(self,class_):
self.class_ = class_
def __call__(self,*args,**kwargs):
if not Son.__instance:
Son.__instance = self.class_(*args,**kwargs)
return Son.__instance
@Son
class Foo(object):
pass
b1 = Foo()
b2 = Foo()
print(id(b1))
print(id(b2))
4.元类方法
class UpperAttrMetaClass(type):
# init方法也可以实现
def __init__(self,*args,**kwargs):
self._instance = None
type.__init__(*args,**kwargs)
# new方法可以实现
#def __new__(cls,class_name,class_parents,class_attr):
# class_attr['_instance'] = None
# return type.__new__(cls,class_name,class_parents,class_attr)
# # 下边这个不可取
# #return type(class_name,class_parents,class_attr)
def __call__(self,*args,**kwargs):
if not self._instance:
self._instance = super().__call__(*args,**kwargs)
return self._instance
# 在代码执行到class FOO这里的时候 元类的__new__方法 和 __init__方法其实已经被执行
class Foo(object,metaclass=UpperAttrMetaClass):
pass
f1 = Foo()
f2 = Foo()
print(id(f1))
print(id(f2))
网友评论