user14622805
user14622805

Reputation:

why I get "AttributeError: class <class name> has no attribute <attribute name>" even I've clearly defined the attribute

I just started programming an assembler for a project, however, I am getting the following error while I am trying to run it. It says that some attribute is not defined even though I have defined it. I don't understand what is happening.

Traceback (most recent call last):
  File "./Assembler.py", line 27, in <module>
    main()
  File "./Assembler.py", line 22, in main
    P = Parser.inst
AttributeError: class Parser has no attribute 'inst'

This is the code.

class Parser:
    def __init__(self, inst, type):
        self.inst = inst.strip()
        self.type = None
        self.checkType()

    def checkType(self):
        if self.inst.startswith('//') or self.inst in ['\n', '\r\n']:
            return

        elif self.inst.startswith('@'):
            self.type = 'A'

        else:
            self.type = 'C'

def main():
    with open(sys.argv[1], 'r') as asm:
        for inst in asm:
                P = Parser.inst
                print(p.type)


if __name__ == "__main__":
    main()

Upvotes: 1

Views: 725

Answers (3)

user17812970
user17812970

Reputation:

In the main function P = Parser.inst should be `P = Parser(inst, None)

Upvotes: 0

quamrana
quamrana

Reputation: 39354

You meant to create an instance of Parser():

def main():
    with open(sys.argv[1], 'r') as asm:
        for inst in asm:
            p = Parser(inst, None)
            print(p.type)

Upvotes: 1

Ali Irani
Ali Irani

Reputation: 607

Parser is a class and didn't have inst value. You must create an instance from Parser and pass inst to it. Also, you have to pass type parameters to your class constructor.

P = Parser(inst, type)

Upvotes: 1

Related Questions