【问题标题】:Python error object() takes no parameters after upgrading python2.7 to python3.4python2.7升级到python3.4后python报错object()不带参数
【发布时间】:2017-11-03 10:25:27
【问题描述】:

bashhostlist.py

from __future__ import print_function
import subprocess
import sys
import logging

class Singleton(object):
    """
    Creating a  single object that will work for all the plugin
    We create an object with an attrubute of the file path which is same for all the plugins
    So rather than creating new object for all the same object works so making singleton
    """
    _instance = None

    def __new__(class_, *args, **kwargs):
        if not isinstance(class_._instance, class_):
            class_._instance = object.__new__(class_, *args, **kwargs)
        return class_._instance


class InventoryMgmt(Singleton): 
    hostlist = {'hostcontent':None}
    def __init__(self, path):
        """ bash file path where environement are set """
        self._scriptpath = path

Singleton 类用于单例模式

错误类型:

python版本3.4出现错误,python2.7不出现错误

错误日志:

2017-11-03 03:09:39,187 - root - INFO - Plugin started
2017-11-03 03:09:39,187 - root - INFO - Trying to fetch from etc_shadow_plugin
2017-11-03 03:09:39,187 - root - ERROR - object() takes no parameters
Traceback (most recent call last):
  File "/home/sjoshi/python3.4/check-acess/plugins/plugin_etc_shadow/plugin_etc_shadow.py", line 91, in run
    listofhost=phelper.getallthehosts(hostnamewithoutdollar, envscriptpath)
  File "/home/sjoshi/python3.4/check-acess/lib/sshplugin/sshplugin.py", line 172, in getallthehosts
    myhosts=hostname.InventoryMgmt(envscriptpath)
  File "/home/sjoshi/python3.4/check-acess/lib/inventory/bashhostlist.py", line 16, in __new__
    class_._instance = object.__new__(class_, *args, **kwargs)

这就是我打电话给班级的方式

myhosts=hostname.InventoryMgmt(envscriptpath)

这也清楚地显示在错误消息中

疑问:

即使存在 init() 方法,它需要一个参数,为什么 是不是抛出了那个错误。最重要的是错误不是 在 python2.7 上运行时在那里

我已经确认不是制表符和间距问题,我看到很多答案都怀疑这个问题,所以

【问题讨论】:

  • @georgexsh 会尽快回复您

标签: python python-3.x singleton python-3.3


【解决方案1】:

您应该删除那些额外的参数。在python2.7中,如果你将额外的参数传递给object.__new__,则会发出DeprecationWarning,但this warning has been suppressed by default,如果你使用-Wdefault开关运行你的脚本,你会看到:

$ python2 -Wdefault singleton.py
singleton.py:13: DeprecationWarning: object() takes no parameters
  class_._instance = object.__new__(class_, *args, **kwargs)
<__main__.InventoryMgmt object at 0x106a2fd90> <__main__.InventoryMgmt object at 0x106a2fd90> True

从 python3.3 开始,此警告已转换为错误。

【讨论】:

    猜你喜欢
    • 2018-12-30
    • 1970-01-01
    • 1970-01-01
    • 2016-07-14
    • 2021-07-03
    • 1970-01-01
    • 2021-11-16
    • 2018-11-12
    • 1970-01-01
    相关资源
    最近更新 更多