Python - 被 class 和实例变量混淆

Python - Confused by class and instance variable

我尝试为 unix 查找命令编写一个小包装脚本。我搞砸了参数传递。你能给我一个关于我的错误的提示吗?

错误信息是

Traceback (most recent call last):
  File "frep.py", line 43, in <module>
    inst.prep_shell_commands(self.extension, self.search_string, self.rel_numbers)
NameError: name 'self' is not defined

这是代码:

import os
import subprocess
import string
import sys


class Frep(object):

    extension = ""
    search_string =""
    commands = []
    rel_numbers = ""


    def get_params(self):
        Frep.no_of_params = len(sys.argv)
        if Frep.no_of_params == 4:
            Frep.extension = str(sys.argv[1])
            Frep.search_string = str(sys.argv[2])
            Frep.rel_numbers = str(sys.argv[3])
        else:
            print "Usage:   frep [FILE_EXTENSION] [SEARCH_STRING] [RELEASE_NUMBERS]"
            print "Example: frep sql my_search_string [5-6]"
            print " "
            sys.exit()


    def prep_shell_commands(self, ext, ss, reln):
        print ext
        tmp_folderlist = string.split(subprocess.check_output("find /data/grep_dir -maxdepth 1 -type d -name '["+reln+"]*'", shell=True), '\n')
        #tmp_folderlist = string.split(subprocess.check_output("find /data/grep_dir -maxdepth 1 -type d -name '[6-7]*'", shell=True), '\n')
        for d in tmp_folderlist:
            commands.append("find " + d + " -type f -name '*" + ext +"' -exec grep -il '" + ss +"' {} \;")
        print commands


    def exec_commands(self, c_list):
        for c in c_list:
            os.system(c)


inst = Frep()

inst.prep_shell_commands(self.extension, self.search_string, self.rel_numbers)

exec_commands(self.commands)

Frep 的实例中,您列出以下内容:

extension = ""
search_string =""
commands = []
rel_numbers = ""

为了能够正确访问这些变量,您需要执行以下操作:

class Frep(object):
    def__init__(self):
        self.extension = ""
        self.search_string = ""
        self.commands = []
        self.rel_numbers = ""

然后,当您在 class 中引用这些变量时,您可以使用 self.variablename

要在 class 之外引用它们,您可以使用 Frep.extension

您使用对象实例的名称调用实例成员

inst.prep_shell_commands(inst.extension, inst.search_string, isnt.rel_numbers)

也就是说,如果您的方法总是要调用实例变量,那么您应该重写 prep_shell_commands 方法,使其不带参数。

此处重写了您的代码。这个版本并不完美,但它展示了如何定义 class 以及如何以通常在 Python 中完成的方式使用 class 实例。

FWIW,在将输入数据传递到您的 class 之前验证输入数据可能更好,但我想这里没问题。

我没有测试过这段代码,因为我没有所需的目录和文件,但希望它不包含任何可怕的错误。 :)

#!/usr/bin/env python

import os
import subprocess
import sys

class Frep(object):
    def __init__(self, args):
        if len(args) != 3:
            self.usage()

        self.extension = args[0]
        self.search_string = args[1]
        self.rel_numbers = args[2]
        self.commands = []

    def usage(self):
        print "Usage:   frep FILE_EXTENSION SEARCH_STRING RELEASE_NUMBERS"
        print "Example: frep sql my_search_string [5-6]"
        print " "
        sys.exit()

    def prep_shell_commands(self):
        print self.extension
        cmd = "find /data/grep_dir -maxdepth 1 -type d -name '[" + self.rel_numbers + "]*'"
        tmp_folderlist = subprocess.check_output(cmd, shell=True).split('\n')

        for d in tmp_folderlist:
            cmd = "find " + d + " -type f -name '*" + self.extension + "' -exec grep -il '" + self.search_string + "' {} \;"
            self.commands.append(cmd)
        print self.commands

    def exec_commands(self):
        for cmd in self.commands:
            os.system(cmd)


def main():
    inst = Frep(sys.argv[1:])
    inst.prep_shell_commands()
    inst.exec_commands()


if __name__ == '__main__':
    main()