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 use magic methods ?

1-why do use magic methods in our class? 2- if we didn't include the (len) magic method, will I not be able to use the len function?

I'm just confused about why I have to write these methods for a simple operation that I can insert a word or symbol to shortcut it all.

Can you link to the video/challenge you are looking at so I can better explain.

1 Answer

For now you may not see the use in these magic methods, however later when working on large projects you will.

If you don't define how these methods will be used for your class, then the interpreter does what it thinks is best, which isn't always what you want. So with these magic methods you can define how your class behaves when dealing with things like adding and using specific operators. I personally like using __str__ as the best example, because if you want to print an object, it will often come out looking horribly, using __str__ we can define exactly what is output when you use print on an object.

So basically when making a class I have to use a magic method for potentially everything that the user will write when using my class, like if he used the (+), he is expecting addition, so I have to use an all additional method to make things run smoothly, right?

Not necessarily, it does depend if you're inheriting from a parent class that will have it defined or not, and what operations you can expect your users to be performing, it is highly unlikely you will have to write a lot of them out for every single class you write. If you know that you will need certain operations to go a certain way you are safer writing them yourself. But before writing any just test how your class behaves when you perform certain operations, you will find out if it behaves as expected or if you need to do it yourself.