TypeError: object.__new__() takes exactly one argument (the type to instantiate)

TypeError: object.__new__() takes exactly one argument (the type to instantiate)

我想用名称 MyClass 实现 class。 这个class应该是一个单例,它必须继承自BaseClass。

最后我想出了以下解决方案:

import random


class Singleton(object):
    _instances = {}

    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs)
        return cls._instances[cls]


class BaseClass(object):
    def __init__(self, data):
        self.value = random.random()
        self.data = data

    def asfaa(self):
        pass


class MyClass(BaseClass, Singleton):
    def __init__(self, data=3):
        super().__init__(data)
        self.a = random.random()


inst = MyClass(3)

如果 MyClass 的 def __init__(self, data=3) 没有任何参数,Evrythig 将正常工作。
否则我会收到错误

line 9, in __new__
cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs)
TypeError: object.__new__() takes exactly one argument (the type to instantiate)

如何向 MyClass 提供任何参数?

所以,你的错误是 TypeError: object.__new__() takes exactly one argument (the type to instantiate)。如果您查看您的代码,您正在做 super(Singleton, cls).__new__(cls, *args, **kwargs)super(Singleton, cls) 指的是 object class 因为你的 Singleton class 继承了 object。你只需要改变这个:

cls._instances[cls] = super(Singleton, cls).__new__(cls, *args, **kwargs)

对此:

cls._instances[cls] = super(Singleton, cls).__new__(cls)

因为 object 不接受任何额外的参数。