1 of 21

Dunder Wonder

Python Magic Methods

  • Joe Mann

2 of 21

Topics Covered

Global special variables (__name__, __all__, etc)

Private and Protected Methods

Magic Methods

3 of 21

Terminology

Under (_) and Dunder (__) methods

_asdict, __supersecretmethod, __eq__

Duck Typing

If it walks like a duck and quacks like a duck, then it must be a duck

4 of 21

5 of 21

Global Variables

6 of 21

Special Global Variables

  • __name__

if __name__ == ‘__main__’:

pass # Do something

  • __builtins__ / __builtin__
  • __doc__
  • __all__

7 of 21

8 of 21

Private and Protected Methods

9 of 21

Private Methods

  • Using the single underscore to designate
  • A convention rather than a strongly enforced standard
    • You can still access class methods that start with ‘_’ outside said class
    • For functions, these won’t be included in ‘from spam import *’
  • Some IDEs and code checkers will warn about access outside of class / module

10 of 21

11 of 21

Protected Methods

  • Using a double underscore (dunder) to designate
  • Also more of a convention than a standard
    • Names are mangled, but it is a predictable pattern
    • This is done to eliminate overriding rather than hiding these methods
  • Really bad (and hacky) to call these outside the class / module

12 of 21

13 of 21

Magic Methods

14 of 21

Magic Methods

  • Construction and initialization: __new__, __init__, __del__
  • Object Representation: __str__, __repr__, __format__
  • Container Methods: __len__, __getitem__, __setitem__
  • Also…. __dict__

15 of 21

16 of 21

17 of 21

18 of 21

Questions?

19 of 21

Magic Methods, cont

  • Binary Operators: __add__, __sub__
  • Uniary Operators: __neg__, __pos__, __abs__
  • Attributes: __getattr__, __setattr__
  • Extended Operators (+=, -=, etc): __iadd__, __isub__
  • Type Conversions: __int__, __long__

20 of 21

21 of 21