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

标签 python deprecated monostate

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

相关文章:

python - 无法从 Python 应用程序连接到 DataStax Enterprise 集群

python - pip在windows中安装密码学

Python西蒙游戏: I Got Stuck Finishing the Sequence

python - 将 Dataframe 列的内容“扩展”到新列中

java - Payload.getIssuee() 已弃用

Kotlin 弃用注解将其替换为类名

facebook - 旧的 Facebook离线访问 token 是否可以在离线访问已弃用的情况下继续使用?

c++ - 在 C++ 中,在单态类/静态成员的析构函数中管理资源是个坏主意吗?

c++ - 具有静态成员的类与单例