Search code examples
stringpython-2.7objectattributeerror

AttributeError: 'str' object has no attribute 'name'


class System:
    def __init__(self,code,name,price):
        self.name = name
        self.price = price
        self.code = code

    def __str__(self):
        return 'Code: ' + self.code + '\tName: '  self.name + \'tPrice: ' + self.price 

    def choose_item(self):
        count = 0
        for item in self.name:
            print str(count) + '\t' item.name + '\t' + item.cost
            count += 1
        question = raw_input('Enter the code: ')
        if question == 0:
            exit()
        elif choice != self.code:
            print 'Invalid code'
        else:
            index = question -1
        name[index].self.choose_item()
        print 'Your item has been added'

I got this error and can't see the mistake. I want to choose items by keying the code so that the item will be added. Not sure is this the correct way to do.

AttributeError: 'str' object has no attribute 'name'

Solution

  • The first two errors are in this function __str__(self) It should be '\tName: ' + self.name + '\tPrice: ' (You have missed + sign and have not included \t inside single quote.)

    return 'Code: ' + self.code + '\tName: ' + self.name + '\tPrice: ' + self.price 
    

    Then in choose_item(self) function. (Missing + sign)

    print str(count) + '\t' + item.name + '\t' + item.cost