Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.Start your free trial
Confusion in code :(
What is different between self.value and self as it both does the same work but Kenneth sir uses both self.value and self, Any explanation?
Chris FreemanTreehouse Moderator 68,423 Points
It is a matter of context. In the
self.value refers to the string value stored in the attribute and
self refers to the
NumString instance object itself.
The built-in method
int() operates on strings. By using
int(self) Kenneth is triggering a call to the class'
__int__ method to convert to an integer. If
int(self.value) were used, then the string contained in
self.value would be pass directly to
int(). It is important to use the
int(self) to be sure that the objects own
__int__ is run in cases where special considerations might be implemented for that class.
Clarification: The builtin type
int can be called as a function
int() to coerce and object into and integer. Internally it knows how to convert numbers and strings to integers (there is no
str.__int__() method) so the
__int__ method would only be called for other object types.
Ray Karyshyn13,443 Points
In Python self represents an instance of the class.
On the other hand, self.value accesses an attribute of the class (in this case the 'value' attribute).
name = "Bob"
return self.name # We retrieve attributes of a class using dot notation