在一个类中的许多方法中定义属性的Python

2024-10-03 23:30:48 发布

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

我创建了两个类:一个用于解析命令行参数,另一个用于从stop words文件获取stop words:

import getopt, sys, re

class CommandLine:
    def __init__(self):
        opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
        opts = dict(opts)
        self.argfiles = args

    def getStopWordsFile(self):
        if '-s' in self.opts: 
             return self.opts['-s']

class StopWords:
    def __init__(self):
        self.stopWrds = set()

    def getStopWords(self,file):
        f = open(file,'r')
        for line in f:
            val = line.strip('\n')
            self.stopWrds.add(val)
        f.close()
        return self.stopWrds

我想要的是打印停止词集,因此我定义了以下内容:

config = CommandLine()
filee = config.getStopWordsFile()
sw = StopWords()
print sw.getStopWords(filee)

以下是命令行:

python Practice5.py -s stop_list.txt -c documents.txt -i index.txt -I

运行代码时,出现以下错误:

if '-s' in self.opts: 
AttributeError: CommandLine instance has no attribute 'opts'

我无法解决的问题是如何从init方法获取opts并在getStopWordFile()方法中使用它。那么这个问题的可能解决方案是什么呢?你知道吗


Tags: 命令行inselftxtinitdefsysargs
2条回答

您忘记在__init__中向opts添加self.

class CommandLine:
    def __init__(self):
        opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
        self.opts = dict(opts)
        self.argfiles = args

将以下方法更改为

def __init__(self):
        opts, args = getopt.getopt(sys.argv[1:],'hs:c:i:I')
        self.opts = dict(opts)
        self.argfiles = args

相关问题 更多 >