报错
有个 service
文件夹导入模块报错:
TypeError: module() takes at most 2 arguments (3 given)
目录与文件
报错的 service
包目录结构如下:
|service
|__init__.py
|Singleton.py
|DB.py
__init__.py
文件:
from service.DB import DB
from service.Singleton import Singleton
DB.py
文件:
from service import Singleton
class DB(Singleton):
def __init__(self, config: dict):
super(DB, self).__init__(config=config)
service
文件夹就是service包
。DB.py
文件就是DB模块
。DB模块
里的DB类
, 继承了service包
的Singleton模块
的Singleton类
解决
把第一行 from service import Singleton
修改为:
from .Singleton import Singleton
或
from service.Singleton import Singleton
单例模块基类
Singleton.py
:
"""
单例模式基类
@link https://www.cnblogs.com/huchong/p/8244279.html
"""
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
meta = {}
def __init__(self, *args, **kwargs):
pass
@classmethod
def get_instance(cls, *args, **kwargs):
if not hasattr(cls, "_instance"):
with cls._instance_lock:
if not hasattr(cls, "_instance"):
cls._instance = cls(*args, **kwargs)
return cls._instance
if __name__ == '__main__':
def task(arg):
obj = Singleton.get_instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task, args=[i, ])
t.start()
time.sleep(5)
obj = Singleton.get_instance()
print(obj)