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.
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 67,995 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).
class Person: name = "Bob" def return_the_name_attribute(self): return self.name # We retrieve attributes of a class using dot notation