Search code examples
pythonclassattributes

How to allow an attribute from class to be accessed?


I have a problem where I keep getting the error AttributeError: 'TableHeight' object has no attribute 'quality' Which I'm assuming is due to the fact that python can't reach it.

This is my code so far and I've indicated the part where the code comes up with an error (it works without it):

class TableHeight:
    def __init__(self, height, quality):
        self.height = height
        self.viewquality = quality
        self.seats = 4


one = TableHeight(height=74, quality=60)
two = TableHeight(height=74, quality=80)
three = TableHeight(height=75, quality=75)


def tabletocombine(tableone, tabletwo):
    tableseats = tableone.seats + tabletwo.seats - 2
    
    if tableone.height != tabletwo.height:                  # Error
        tableone.quality - 10                               # Error
        desirability = tableone.quality + tabletwo.quality  # Error
    else:                                                   # Error
        desirability = tableone.quality + tabletwo.quality  # Error

    print(tableseats)
    print(desirability)


tabletocombine(one, two)

I'm expecting the code to combine the desirability attributes if the height is the same and subtract 10 from one of the attributes than adding them if the heights are different. This is later put into the desirability variable and printed out into the console. (But I can't get this part to work for me)


Solution

  • The problem is you're calling the wrong field name.

    • Either in tabletocombine function:

    Where you have tabletwo.quality you should use tabletwo.viewquality, as you have defined self.viewquality in your __init__ method.

    • OR in your __initi__ method:

    You could change self.viewquality = quality to self.quality = quality and the code should also work.