Skip to content

Latest commit

 

History

History
38 lines (20 loc) · 1.55 KB

magic_methods.md

File metadata and controls

38 lines (20 loc) · 1.55 KB

Magic or Dunder Methods

Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action.

These are commonly used for operator overloading.

-  Built-in methods are faster than dunder ones

  • If you only implement one of these special methods, choose repr, because when no custom str is available, Python will call repr as a fallback.

-The default implementation is useless (it’s hard to think of one which wouldn’t be, but yeah)

  • repr goal is to be unambiguous (usually debugging)

  • str goal is to be readable (The goal is to represent it in a way that a user, not a programmer, would want to read it)

  • Container’s str uses contained objects’ repr

Magic methods in Python are the special methods that start and end with the double underscores. They are also called dunder methods. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action. For example, when you add two numbers using the + operator, internally, the add() method will be called.

Built-in classes in Python define many magic methods. Use the dir() function to see the number of magic methods inherited by a class

>>> num=12

>>> str(num)

'12'

>>> #This is equivalent to

>>> int.__str__(num)

'12'

Basically, bool(x) calls x.bool() and uses the result. If bool is not implemented, Python tries to invoke x.len() , and if that returns zero, bool returns False . Otherwise bool returns True