Python magic methods

Python magic methods or Dunder methods

Python magic methods are the functions which are predefined in python and performs some special task.  These are surrounded by the double underscores that is why these are also called Dunder methods” . These methods let us simulate the python’s built in behaviour. Some common dunder functions are __init__, __str__, __repr__ , __del__ .

In this article we will learn:

  • What are magic functions?
  • What is operator overloading?
  • __init__
  • __del__
  • __repr__
  • __str__
  • __add__
  • __doc__
  • __len__

What is operator overloading ?

Operator overloading is a specific case of OOP polymorphism in which some or all operators like += or == are treated as polymorphic functions and as such have different behaviors depending on the different situations.

 

Example

operator overloading
operator overloading

Output

output: operator overloading
output: operator overloading

In above example, there are four variables, two of them are type integers and other type string. So the operator “+” performs different operations (Addition in case of integer values and concatenation in case of string values), so this concept is known as Operator overloading.  This concept becomes more familiar to us with magic functions.

__init__

It is one of the most widely used python magic function , used to initialize values of a class object. The  __init__ method calls automatically, when object of class is created. It returns none (nothing). It is used as constructor in python. If you want to learn more about constructor and destructor (__del__) in python then you can visit:

http://onlinetutorial.co.in/constructor-in-python/

 

__del__

We use this __del__ function to deallocate resources from objects . So it is used as destructor in python. Like constructor, it will call immediately when object is created, so there is no need to call destructor function.

Example

python special methods
python special methods

Output

output: python magic methods
output: python magic methods

As you can see __init__ and __del__ calls automatically when we create object of class instead of:

obj.__init__()

__str__ , __repr__

__str__ and __repr__ are python magic methods which are we use to create a string representation of an object. Both of these methods returns a string value.

if  we define __repr__ and not __str__ , the object will behave as though __str__ == __repr__

This means, in simple terms: almost every object you implement should have a functional __repr__ that’s usable for understanding the object. Implementing __str__  is optional: do that if you need a “pretty print” functionality (for example, used by a report generator).

In normal words we can say:

  • __str__ returns a string which is convenient to end-users
  • __repr__ returns a string which is more convenient to debuggers or developers
  • If we use __str__ or __repr__ actually what is going on background:
objname.__str__()

or

objname.__repr__()

Example

python magic methods
python magic methods

Output:

output: python magic methods
output: python magic methods

__add__

It is also an special method, which automatically calls when we create instance of class. __add__ allows us to add some string or integer data to object previous attributes. It allows operator overloading which we discussed earlier. When we call add(), every time there happens following at background:

int.__add__(operand1, operand2,...,operandN)  #for integers

str.__add__(operand1, operand2,...,operandN) #for strings

To understand how __add__ works, you can directly add variables using above syntax.

For example:

int.__add__(10,20)

str.__add__('a','b')

Output

30

ab

 

 

Example

python magic methods
python magic methods

Output

output: python magic methods
output: python magic methods

In above example, we have used __add__ to add to class data members. You can also see here __add__ behaves differently in different situation (string and integers) hence operator overloading. If you not use __add__ ( check by remove __add__ function) , then you will see error like this:

Traceback (most recent call last):
File "methods.py", line 8, in <module>
print(myobj+10)
TypeError: unsupported operand type(s) for +: 'Student' and 'int'

__doc__

It is an magic function, used to print the documentation string of the class or member function.  The main purpose to add documentation string in  code is to just make code easy to understand by programmers.

Example

python magic methods
python magic methods

Output

python magic methods
output: python magic methods

__len__

We use this function to return the length of string objects or data-members. It woks similar to python’s built in len() method.

Syntax

"String".__len__()

or

stringName.__len__()

#similar to built in function

len('string')

Example

python magic functions
python magic functions

Output

output: python magic methods
output: python magic methods

So these are some common python magic methods (or dunder / special methods).

 

73 thoughts on “Python magic methods

Leave a Reply

Your email address will not be published. Required fields are marked *

  1. Just about all of what you say is supprisingly precise and it makes me ponder why I had not looked at this in this light previously. Your article really did switch the light on for me personally as far as this particular subject matter goes. But there is actually 1 issue I am not too comfortable with so whilst I attempt to reconcile that with the main idea of the position, permit me observe just what the rest of the readers have to say.Very well done.

  2. Admiring the time and energy you put into your website and in depth information you provide. It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed information. Wonderful read! I’ve saved your site and I’m adding your RSS feeds to my Google account.

  3. It is perfect time to make some plans for the longer term and it’s time to be happy. I’ve read this put up and if I may just I wish to counsel you some fascinating issues or tips. Perhaps you could write subsequent articles referring to this article. I wish to learn more things about it!

  4. Wonderful paintings! That is the kind of info that are meant to be shared across the web. Disgrace on the seek engines for no longer positioning this post upper! Come on over and consult with my site . Thank you =)

  5. great post, very informative. I’m wondering why the other specialists of this sector do not realize this. You must proceed your writing. I am confident, you have a huge readers’ base already!

  6. Fantastic goods from you, man. I have understand your stuff previous to and you are just too fantastic. I really like what you have acquired here, really like what you’re saying and the way in which you say it. You make it enjoyable and you still care for to keep it wise. I cant wait to read far more from you. This is actually a great site.

  7. I would like to thnkx for the efforts you have put in writing this website. I am hoping the same high-grade site post from you in the upcoming also. Actually your creative writing skills has encouraged me to get my own web site now. Actually the blogging is spreading its wings fast. Your write up is a good example of it.

  8. Its such as you learn my mind! You seem to understand so much about this, such as you wrote the e book in it or something. I feel that you just could do with some p.c. to force the message home a bit, however instead of that, this is fantastic blog. A great read. I’ll certainly be back.

  9. I just want to mention I am just newbie to blogging and site-building and really loved this web site. Almost certainly I’m want to bookmark your site . You certainly come with fantastic well written articles. Thank you for sharing with us your web site.

  10. produce,Document represented too much time for too long to say I do have sick, how could you nevertheless hardly understand? I personally jot far too much too much We now have written and published depleted, you continue to don’t get precisely how

  11. Hey! I know this is kinda off topic but I was wondering which blog platform are you using for this website? I’m getting tired of WordPress because I’ve had issues with hackers and I’m looking at options for another platform. I would be fantastic if you could point me in the direction of a good platform.

  12. It’s perfect time to make some plans for the future and it is time to be happy. I’ve read this post and if I may just I want to counsel you few fascinating issues or advice. Perhaps you can write next articles relating to this article. I desire to learn more issues about it!

  13. Howdy would you mind stating which blog platform you’re using? I’m going to start my own blog in the near future but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique. P.S My apologies for getting off-topic but I had to ask!

  14. Great – I should certainly pronounce, impressed with your web site. I had no trouble navigating through all tabs as well as related info ended up being truly simple to do to access. I recently found what I hoped for before you know it at all. Quite unusual. Is likely to appreciate it for those who add forums or something, website theme . a tones way for your customer to communicate. Excellent task..

  15. Great work! That is the kind of information that are supposed to be shared across the web. Shame on Google for now not positioning this put up higher! Come on over and talk over with my website . Thanks =)

  16. Hey there! This post couldn’t be written any better! Reading this post reminds me of my good old room mate! He always kept talking about this. I will forward this page to him. Fairly certain he will have a good read. Thank you for sharing!

  17. You actually make it seem so easy with your presentation but I find this topic to be actually something that
    I think I would never understand. It seems too complicated and extremely
    broad for me. I’m looking forward for your next post, I’ll try to get the hang of it!

  18. My spouse and I stumbled over here by a different website and thought I should check things out. I like what I see so now i am following you. Look forward to going over your web page for a second time.

  19. What i don’t understood is actually how you are now not actually a lot more smartly-favored than you may be now. You’re so intelligent. You understand thus considerably on the subject of this topic, produced me in my opinion consider it from numerous numerous angles. Its like women and men are not involved except it is one thing to do with Lady gaga! Your individual stuffs great. At all times deal with it up!

  20. An impressive share, I just given this onto a colleague who was doing a little analysis on this. And he in fact bought me breakfast because I found it for him.. smile. So let me reword that: Thnx for the treat! But yeah Thnkx for spending the time to discuss this, I feel strongly about it and love reading more on this topic. If possible, as you become expertise, would you mind updating your blog with more details? It is highly helpful for me. Big thumb up for this blog post!

  21. Игровые автоматы PlayFortuna. Получи бонус 50 бесплатных вращений здесь >>> https://casino-avtomati-onlain.com/the-best-casino/play-fortuna-casino.html
    Казино на доллары, евро. Минимальный депозит 1 доллар. 350 лицензионных игровых автоматов. ТОП казино онлайн Play Fortuna casino. Лучшие игры, лучшие бонусы, быстрые выплаты. Реальные игры, на реальные деньги.

  22. Бывает так, что мужчинам не хватает интересного портала, где есть возможность смотреть крутые статьи и новости на разные темы. Найти сайт без афиш, где публикуются только самые свежие факты и события – тяжело. Хотя, много интересных новостей реально смотреть на сайте https://zaxvatu.net/1-arkhiv/

    Каждый день на портал добавляются обновленные статьи на различные тематики. Если вы увлекаетесь домом, вы вероятно можете найти старинные рецепты. Как правило на веб-сайте часто добавляются статьи правил этикета. Для многих мам будет интересен блок здоровья.

    В нём любой интересующийся сможет просмотреть информацию по поводу интимной гигиены. Если ранее вы ничего не знали о ущербе определённых ингредиентов в пище, то после просмотра новостей на веб-сайте у вас откроются глаза на конкретные вещи. Так, например, вы сможете узнать то, что требуется употреблять еженедельно. Дополнительно вам будет доступна информация о том, что может быть вредным и приносить сложности вам и вашему телу.

    Если вы наблюдаете за своим питанием, употребляете только вкусную и полезную пищу, то на площадке есть справка и про метаболизм. А в случае проблем со здоровьем, вы узнаете без рекомендаций докторов инфо насчет лечения определенных болезней. Если вам пришлось столкнуться ранее со сложностями в любовном вопросе, то ряд нужных факторов, которые смогут помочь возбудить как мужчину, так и женщину – размещены на портале.

    Для любителей отдыхать и путешествий также найдётся необходимая информация. Если вы зайдёте на zaxvatu.net, то имеете шанс выбрать интересные варианты отдыха по доступным ценам. Информация будет интересна даже тем, кто живёт в крупном городе и прежде редко посещал какие-то места. У вас откроется вероятность посетить украинские горы в Карпатах или снять комнату в Италии по цене квартиры вашего города.

    Данные о последних новинках авто, разного рода инновации и много чего другого – всё это вы сможете прочитать на странице. Руководство постоянно обновляет ленту и публикует исключительно самые важные новости и лайфхаки.

  23. Ш.: мы с димой снимаем квартиру в киеве, живем вместе. В соответствии с оригинальным британским форматом diet on. Литературного форума можно будет купить книжные новинки по цене из.. Таблетки для похудения – не всегда безобидные средства; многие да, для когото таблетки для похудения xls разновидности самые эффективные таблетки для похудения..

Please wait...

Subscribe to our newsletter

Want to be notified when our article is published? Enter your email address and name below to be the first to know.