Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/variables/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python在一个类中的许多方法中定义属性_Python_Attributeerror - Fatal编程技术网

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

Python在一个类中的许多方法中定义属性,python,attributeerror,Python,Attributeerror,我创建了两个类:一个用于解析命令行参数,另一个用于从停止字文件中获取停止字: 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(sel

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

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()方法中使用它。那么这个问题的可能解决方案是什么呢?

您忘了在
\uuu init\uuu
中添加
self.
opts

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
opts=dict(opts)
-->
self.opts=dict(opts)
<代码>自我。
opts=dict(opts)