全局名称在self/class中?

2024-09-29 21:52:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我在类中调用变量时遇到问题。我把所有的事情都安排好了,但我还是犯了错误。我想我很难弄清楚这一点,因为我是3.0脚本新手。在

这是我的剧本:

http://pastebin.com/9Lrw399E

错误如下:

command = 'tcpdump -c5 -tttt -w {0} host {1}'.format(raw, input_host)
NameError: global name 'raw' is not defined

如果我做的话自我。原始或者self.input_主机在

它得到这个:

^{pr2}$

Tags: 脚本comhttphostinputraw错误事情
2条回答

试试看

command = 'tcpdump -c5 -tttt -w {0} host {1}'.format(self.raw, self.input_host)

除非将raw和input_host作为函数参数传入,否则需要使用自变量查找类实例的变量。在

编辑:您还需要确保任何函数定义自我。原始以及self.input_主机在运行这行代码之前调用。从代码中,如果您调用MainLoop.cmd(),则必须在cmd()之前调用MainLoop.host()和{},这样self.raw和{}存在于类的实例中。在

在这种情况下,您可能应该为类创建一个至少创建实例变量的构造函数

^{pr2}$

然后检查自我。原始以及self.input_主机在创建命令之前。在

def cmd(self):
    if self.raw is not None and self.input_host is not None:
        command = 'tcpdump -c5 -tttt -w {0} host {1}'.format(self.raw, self.input_host)
        subprocess.call(command.split(), shell=False)
command = 'tcpdump -c5 -tttt -w {0} host {1}'.format(raw, input_host)

应该是:

^{pr2}$

注意self。在

相关问题 更多 >

    热门问题