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.
how to call dunder methods?
Is there a relationship between dunder methods and the function call? For instance,
class Something: def __amethod__(self): pass x = Something() amethod(x)
I tried this, it does not work. But when I see functions like
float(something), I think we can do this because they are the so called magic functions. Normally we have to call a method
But every now an then there is a method that works like
[MOD: added ```python formatting -cf]
Chris FreemanTreehouse Moderator 67,464 Points
Hey Özgür Yildirim, good question.
The Special methods or Dunder methods are not intended to be called directly. It is also not recommended that a user define their own dunder methods.
Each existent dunder method has been defined to handle a class’s behavior under various contexts. Some of these contexts, as you mentioned, are invoked directly by the user.
int(some_object) says call the
some_object.__int__() method so the some_object’s class can respond how it wishes to behave in an integer context. This would be is usually to return an integer value, but it may be to raise a TypeError saying “I can not be used in an integer context!”
One exception to calling a dunder method would be though the use of a
super() call. This is when you wish to alter the behavior of an inherented dunder method from a parent class.
I’m curious as to the reason you would like to call a dunder method.
Post back if you need more help. Good luck!!!
Thanks Chris, it got more clear now. I was only confused by the concepts of dunder methods, magic methods, and built-in functions. Because we can use certain functions with objects or variables without having ever defined anything. For a brief time I led myself to believe that I can create the same type of functions if I just dunder it. Now I understand that they are limited in number and correspond to certain operations, such as len() bool() int() float() str() print() == != > >= < >= + += * *= / /= - -= is and in.