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.
Understanding how methods in classes work.
I️ only understand how all these methods work in a class. So all the methods run automatically and bounce code back and forth. Like does the dunder add method run, get an error, pass it to dunder radd and the. This passes t back to dunder add?
And if so, is this how all methods in a class run after being initialized?
Steven Parker218,583 Points
Special ("magic") methods like "
__add__" run when you perform a certain operation on a member of the class. In this case, it would be when you add ("+") class instances together, or add another object to it.
__add__" fails or is not present, it will try "
__radd__" to handle the operation. But in that case it will not pass anything back to "
For more information, see Emulating Numeric Types in the Python reference documentation.
So all these methods run in order, down the line? So if an int can't be read, it will automatically move down to float(), etc?
last question -
- I'm still not understanding why we have to define all these functions for float, str, int, etc. Before we were just able to use them as built in functions that python possessed. Why in a class do we have to do this?
Steven Parker Hi, I have always loved your detailed explanation on questions/subject.
I am learning python and sometimes feel like I need to work more on the algorithms and logical reasoning.
Can you please suggest any reference links which will help improve my logic and understanding of python.
@Steven Parker, Thanks!