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.
Begana ChoiCourses Plus Student 13,122 Points
Still confused with self and self.value
I'm still confused with self and self.value concept.
I can understand that self.value is just an attribute of self
and self and Numstring itself.
but why don't we use self.value for add method and other methods for add?
class Numstring: def __init__(self, value): self.value = str(value) def __str__(self): return self.value def __int__(self): return int(self.value) def __float__(self): return float(self.value) #from here, why don't we use self.value ?? def __add__(self, other): if '.' in self.value: return float(self) + other return int(self) + other def __radd__(self, other): return self + other def __iadd__(self, other): self.value = self + other return self.value
By this point in the code, we have already defined the
__float__() method, so we can just convert the whole object (
self) to a float. It's handier to have separate values for
str versions and
float versions rather than keep converting
self is the whole object, and
self.value is the value of
self as a
self.value is an attribute.
Also, sorry, I didn't quite read the code when I answered earlier, I should have said that we can't use
self.value because it's a
str but we can't use
self because it's a
Numstring. We have to convert them.
If you look higher up in the code, you see that
self.value is actually an
def __init__(self, value): self.value = str(value)
If we tried to use
self.value for the arithmetic methods (
__radd__ etc.), we would get an error, because it would be adding an
str to an
float. So, we convert
self.value to a number datatype (
float) so it is a valid datatype to do maths with. I hope this helps!