Search code examples
pythonattributeerror

Python defining an attribute in many methods within one class


I created two classes: one for parsing a command line arguments and the other for getting the stop words from stop words file:

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

What I want is to print the stop words set, therefore I defined the following:

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

Here is the command line:

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

When I run the code, I got this error:

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

The problem that I couldn't solve is how to get the opts from init method and use it inside the getStopWordFile() method. So what is the possible solution for this issue?


Solution

  • change the following method to

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