Mostly Linux & Python syntax notes and hyperlinks.

Thursday, March 24, 2016

python: a little bit about dunder functions

What I learned from looking at Fluent Python yesterday:
  • Functions defined with surrounding double-underlines (“dunder”) are called differently
    •  e.g. len(my_object) instead of my_object.len()
  • In general, we shouldn’t create new dunder  functions
    • One reason is that newer versions of Python might use the same name
  • __repre__ is called by __str__ if no __str__ defined, so it’s more important to define __repre__()  
  • If no __bool__ defined, then python uses __len__() and returns False if 0, True otherwise

No comments:

Post a Comment