Python magic methods

From wikinotes

Python has magic methods, which if defined for a type can alter how an object behaves.

Documentation

class magic methods https://docs.python.org/3/reference/datamodel.html

Tutorials

https://rszalski.github.io/magicmethods/

module

__name__ the module's name (as a string)
__file__ the filepath to the module

class

overview

__new__
__init__
__name__ the class's name (as a string)
__getattr__ obtain value of attribute from a class myinstance.a
__setattr__ set value of attribute on a calss myinstance.a = 'b'
__getitem__ obtain list/dict item by key myinstance['a']
__setitem__ set list/dict item by key myinstance['a'] = 'b'
__len__ called when len(obj)
__contains__ called when if N in obj.
__bool__, __nonzero__ if N (bool is python3).
__hash__ makes your object hashable. (generally, use hash(repr(self))

comparison

__eq__ a == b
__ne__ a != b
__lt__ a < b
__gt__ a > b
__le__ a <= b
__ge__ a <= b

context manager

A context-manager object allows you to use it in a with statement. When either an unhandled exception is raised, or the function exits successfully, __exit__ is called.

This basically bundles the behaviour of try/finally into the class itself.

__enter__ run when used in with statement
__exit__> run on exception, or exit
class A(object):
    def __init__(self):
        pass
    def __enter__(self):
       pass
    def __exit__(self, exc_type, exc_val, exc_tb):
        pass
with A() as a:
    # do stuff

bool

instance

__class__ the object of the class this object is an instance of.