沙滩星空的博客沙滩星空的博客

Python导入模块报错:TypeError: module() takes at most 2 arguments (3 given)

报错

有个 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)
  1. service 文件夹就是 service包
  2. DB.py 文件就是 DB模块
  3. 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)
未经允许不得转载:沙滩星空的博客 » Python导入模块报错:TypeError: module() takes at most 2 arguments (3 given)

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址