0

I'm trying to obtain an instance variable from an instantiated class. The class I've created represents a Stamp.

In this case I'm trying to access the self.cost instance variable as a float in the global environment. To paint a bit more of the picture, my program will generate multiple 'Stamp' classes to add to a shopping cart.

I want to be able to total their respective prices to give a total cost amount. I've tried to only present the relevant bits of code below.

The error I'm receiving is - TypeError: unsupported operand type(s) for +=: 'int' and 'method'

The error is obviously occurring at total cost += cost, although I don't understand why the program is reading the cost as a method and not a float.

See relevant code form within the class below:

self.quantity = int(input("How many of this item would you like to post?)) 
    self.cost = self.price * self.quantity

def get_cost(self):
    return float(self.cost)

And code for the global environment:

stamp = Stamp()           #instantiate a stamp class
totalCost = 0             #create a variable for the totalCost 
cost = stamp.get_cost     #create variable to obtain stamp cost from within class
totalCost += cost         #each time a class is instantiated this will add the cost
baduker
  • 19,152
  • 9
  • 33
  • 56
  • 1
    Get rid of the `get_cost` method and just access `self.cost` directly. Getters are unpythonic, and if you really need them [define them as properties](https://stackoverflow.com/questions/6618002/python-property-versus-getters-and-setters). (And if you really want a getter _method_, then you have to _call_ it to get the value.) – Aran-Fey Apr 05 '18 at 11:33
  • Thanks @Aran-Fey. I'm new to coding and it still amazes me the simplicity to some problems and solutions. – Thomas Swain Apr 05 '18 at 11:40

2 Answers2

0

add () at the end: cost = stamp.get_cost()

Ivan Vinogradov
  • 4,269
  • 6
  • 29
  • 39
0

You just need to add parenthesis when calling get_cost()

cost = stamp.get_cost()

The reason your code didn't cause an error is because in Python, functions are first-class objects, i.e. you can use them as arguments to other functions, assign them to a variables etc.

In your code you were assigning the actual function itself to a variable, rather than calling the function, and having the return value assigned.

For more on this read up on functional programming languages (here's a good article https://www.quora.com/Is-Python-a-functional-language)

Kate Hanahoe
  • 166
  • 8