【问题标题】:AttributeError: 'Object has no attribute'AttributeError: '对象没有属性'
【发布时间】:2019-02-20 14:59:51
【问题描述】:

我有以下代码块:

class HwSwitch(object):

    def __init__(self):
        pass

    def _create_channel(self):
        try:
            self.channel = self.ssh.invoke_shell()
        except SSHException:
            raise SSHException("Unable to invoke the SSH Command shell")

    def _send_cmd_to_channel(self, cmd):
        try:
            time.sleep(1)
            self.channel.send(cmd + '\r\n')
            out = self.channel.recv(9999)
        except SSHException:
            raise SSHException("Execution of command '%s' failed" % cmd)
        return str(out)

但我总是收到错误消息:AttributeError: 'HwSwitch' object has no attribute 'channel'。 似乎问题出在self.channel.send(cmd + '\r\n') 的某个地方,但我看不到在哪里。有什么问题(可能是缩进?)。谢谢

【问题讨论】:

  • 你能添加一个运行代码的例子吗?我想你还没有打电话给_create_channel
  • 注:如果是缩进,则会引发 IndentationError 或 SyntaxError,而不是 AttributeError。
  • 您只在_create_channel 方法中设置self.channel,而不是在__init__ 构造函数中。这意味着如果你在不调用_create_channel 方法的情况下触摸它,你将面临这个错误,我猜这会发生什么。要么添加到__init__,要么从__init__ 调用_create_channel

标签: python python-3.x


【解决方案1】:

您正在将“通道”作为实例变量访问,要么在 __init__ 中创建它,要么在调用 _send_cmd_to_channel 之前调用 _create_channel

另请参考this

【讨论】:

    猜你喜欢
    • 2012-12-01
    • 2021-04-19
    • 2021-11-22
    • 1970-01-01
    • 2018-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-23
    相关资源
    最近更新 更多