Welcome to the Treehouse Community
The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.
Does Python try to convert any instance to an, e.g., int or float when doing math?
When we modified add to be:
def __add__(self, other): if '.' in self.value: return float(self) + other return int(self) + other
Is python trying to convert NumString (self) to a float or int? I get the same result if I get self's value:
def __add__(self, other): if '.' in self.value: return float(self.value) + other return int(self.value) + other
Here python would be converting a string (self.value) to a float or int right? Which one is the best approach?
Cooper Runstein11,834 Points
The dunder methods float and str are called when you do str(self) or float(self), and you've set them to point to self.value. I would use the first method because add will work no matter what you make str and float point to. If for some reason you decided to make the value of your class be self.value + something else, your add function will use a different value than if you were to simply check for the int value of your class, and that could create a bug that would be hard to solve.