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

Python Object-Oriented Python Advanced Objects Math

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 int(something) or float(something), I think we can do this because they are the so called magic functions. Normally we have to call a method objectofsometype.oneofitsmethods(anargument) But every now an then there is a method that works like aspecialmethod(aspecialtypeofobjectthatworkswiththemethod, someoptionalargument)

[MOD: added ```python formatting -cf]

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 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.

For example, 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.