- 使用模块
class myclass( ):
def fun(self):
pass
instance = myclass()
import myclass
a = myclass.instance
__new__
- myclass.py
__new__()
函数只能用于从object继承的新式类
发现实例化对象的时候,调用__init__()
初始化之前,先调用了__new__()
方法
__new__()
必须要有返回值,返回实例化出来的实例,需要注意的是,可以return父类__new__()
出来的实例,也可以直接将object的__new__()
出来的实例返回
import threading
class myclass(object):
_instance_lock = threading.Lock()
def __init__(self):
pass
def __new__(cls, *args, **kwargs):
with myclass._instance_lock:
if not hasattr(myclass, "_instance"):
myclass._instance = object.__new__(cls)
return myclass._instance
from myclass import myclass
obj1 = myclass()
obj2 = myclass()
print(obj1,obj2)
def task(arg):
obj = myclass()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
__call__
(metaclass方式)
- myclass.py
1.类由type创建,创建类时,type的__init__
方法自动执行,类() 执行type的 __call__
方法(类的__new__方法,类的__init__方法)
2.对象由类创建,创建对象时,类的__init__
方法自动执行,对象()执行类的 __call__
方法
import threading
class myclass_template(type):
_instance_lock = threading.Lock()
def __call__(cls, *args, **kwargs):
with myclass_template._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = super(myclass_template,cls).__call__(*args, **kwargs)
return cls._instance
class myclass(metaclass=myclass_template):
def __init__(self):
pass
obj1 = myclass()
obj2 = myclass()
print(obj1,obj2)