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

Why do we need Magic Methods in classes

Hi sorry if this question might be a bit vague, while I understand how to use Magic Methods in a class, I don't understand why we need to use them. Why is it that outside of a class we can use +,*,- without having to use magic methods, but inside a class, we have to set up multiple methods? Thank you

1 Answer

Steven Parker
Steven Parker
229,786 Points

Primitive types already have method implementations for the standard math operations. But you need to implement your own methods for custom objects because the system doesn't know offhand what the operations should do to the objects.

For example, if you had objects that represented cars, what would it mean to add (+) one car to another? Should it return a tuple with both cars in it? Or should it return a single car object that has properties from both originals? You get to make these decisions when you implement the methods.