Monostate __new__ 的 Python 弃用警告 - 有人能解释一下原因吗?
我有一个带有 Python 2.6 的基本 Monostate。
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)
似乎没问题。有人可以用外行的术语解释一下为什么这是一个问题。我理解“这与其他内置函数不一致,例如列表”,但我不确定我是否理解原因。有人能解释一下这告诉我正确的方法吗?
谢谢
I have a basic Monostate with 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", )
Which happily gives me the following Deprecation warning..
untitled:4: DeprecationWarning: object.__new__() takes no parameters
self = object.__new__(cls, *args, **kwargs)
After a bit of googling I find this is attached to Bug #1683368. What I can't figure out is what this means. It's complaining about the following line
self = object.__new__(cls, *args, **kwargs)
Which appears to be OK. Can someone explain in laymens terms why this is a problem. I understand that "this is inconsistent with other built-ins, like list" but I'm not sure I understand why. Would someone explain this show me the right way to do it?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
请参阅 python-singleton-object-instantiation,并注意 Alex Martelli 的 单例示例:
__new__ 弃用
问题是 Guido 回答:See python-singleton-object-instantiation, and note Alex Martelli's singleton example:
The
__new__ deprecation
question was answered by Guido:该警告来自这样一个事实:
__new__()
可以有参数,但由于它们在任何地方都被忽略,因此将参数(除了 cls)传递给它会导致警告。传递额外参数实际上(目前)并不是一个错误,但它们没有任何效果。在 py3k 中,传递 args 会出错。
The warning comes from the fact that
__new__()
can HAVE args, but since they're ignored everywhere, passing args (other than cls) to it causes the warning. It's not actually (currently) an error to pass the extra args, but they have no effect.In py3k it will become an error to pass the args.