- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我有一个基本的 Monostate 和 Python 2.6。
class Borg(object):
__shared_state = {}
def __new__(cls, *args, **kwargs):
self = object.__new__(cls, *args, **kwargs)
self.__dict__ = cls.__shared_state
return self
def __init__(self, *args, **kwargs):
noSend = kwargs.get("noSend", False)
reportLevel = kwargs.get("reportLevel", 30)
reportMethods = kwargs.get("reportMethods", "BaseReport")
contacts= kwargs.get("contacts", None)
a = Borg(contacts="Foo", noSend="Bar", )
这很高兴地给了我以下弃用警告..
untitled:4: DeprecationWarning: object.__new__() takes no parameters
self = object.__new__(cls, *args, **kwargs)
经过一些谷歌搜索后,我发现这是附加到 Bug #1683368 的.我想不通的是这意味着什么。它提示以下行
self = object.__new__(cls, *args, **kwargs)
这似乎没问题。有人可以用外行 的术语解释为什么这是一个问题。我明白“这与其他内置函数不一致,比如列表”,但我不确定我明白为什么。有人可以解释一下,告诉我正确的方法吗?
谢谢
最佳答案
参见 python-singleton-object-instantiation , 并记下 Alex Martelli's单例示例:
class Singleton(object):
__instance = None
def __new__(cls):
if cls.__instance == None:
__instance = type.__new__(cls)
__instance.name = "The one"
return __instance
__new__ deprecation
问题是 answered by Guido :
The message means just what it says. :-) There's no point in calling object.__new__() with more than a class parameter, and any code that did so was just dumping those args into a black hole.
The only time when it makes sense for object.__new__() to ignore extra arguments is when it's not being overridden, but __init__ is being overridden -- then you have a completely default __new__ and the checking of constructor arguments is relegated to __init__.
The purpose of all this is to catch the error in a call like object(42) which (again) passes an argument that is not used. This is often a symptom of a bug in your program.
--Guido
关于Monostate __new__ 的 Python 弃用警告——有人可以解释原因吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1590477/
我是一名优秀的程序员,十分优秀!