I am writing a class ExerciseSession which pulls in the duration, and intensity, and then returns the calories burned in a method within. With an additional setter, the code runs properly with the initial call, but when the data is changed, it returns a Type Error - int not callable, after the setter updates the data. I'm not sure what's wrong - when I've debugged it line by line, it is changing the data properly, so the code should run. Since it DOES run the first time, I'm sure I'm missing something obvious. Here are my setter details:
def set_exercise(self, new_name):
self.name = new_name
def set_intensity(self, new_intensity):
self.intensity = new_intensity
def set_duration(self, new_duration):
self.duration = new_duration
def calories_burned(self):
self.calories_burned = 0
if self.intensity == "Low":
self.calories_burned = str(4 * self.duration)
elif self.intensity == "Medium":
self.calories_burned = str(8 * self.duration)
elif self.intensity == "High":
self.calories_burned = str(12 * self.duration)
return self.calories_burned
Again - when you call a print on a change to an instance, that's when it returns the error, even though it successfully changes the data.
I've reordered, defined the calories burned in the constructor, and even set a setter for calories burned, but the error remains the same. As you can see I've even tried changing the type - but then I get the Type error - str object not callable...
CodePudding user response:
Your error is right here:
def calories_burned(self):
self.calories_burned = 0
You've defined a function named calories_burned
, but after you run it the first time, it shadows itself by defining an instance variable with the same name. If you try calling the method a second time, you'll instead be trying to call the integer, which gives you the error you describe.
Pick a different name for either the method or the attribute. A leading underscore is sometimes a popular way to name internally used attributes: self._calories_burned
. Or, since the attribute doesn't appear to be used anywhere outside of the method body, you might consider getting rid of the attribute all together, and just using a local variable to do the calculations on: calories_burned
, rather than self.calories_burned
. It's also a bit suspect that you're using the same variable name for both an integer, and a string later on. Python doesn't require you to bind only a single type to a given name, but it's usually good design to do so, if only so that you always know what type it contains without any ambiguity.
CodePudding user response:
"Type error - str object not callable..." might mean that you have overridden the "str" function in the code preceding this code snippet. Can you try to print(str)
or print(int)
and let us know what it says? If you append whole code it might also be easier to find the problem. I did not notice any problem with the code snippet you shared here.