gpt4 book ai didi

Monostate __new__ 的 Python 弃用警告——有人可以解释原因吗?

转载 作者:太空狗 更新时间:2023-10-30 00:58:05 25 4
gpt4 key购买 nike

我有一个基本的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com