TypeError: object.__new__() takes exactly one argument (the type to instantiate)(TypeError:Object.__new__()只接受一个参数(要实例化的类型))
问题描述
我想实现名为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
不接受任何其他参数。
这篇关于TypeError:Object.__new__()只接受一个参数(要实例化的类型)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:TypeError:Object.__new__()只接受一个参数(要实例化的类型)


基础教程推荐
- 如何在Python中绘制多元函数? 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01