TypeError:Object.__new__()只接受一个参数(要实例化的类型)

2022-02-27 00:00:00 python inheritance singleton

问题描述

我想实现名为MyClass的类。 此类应该是单例的,并且它必须从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类,因为您的Singleton类正在继承object。您只需更改此设置:

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

至此:

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

因为object不接受任何其他参数。

相关文章