Skip to content

Latest commit

 

History

History
24 lines (24 loc) · 1.51 KB

magic-methods-table.md

File metadata and controls

24 lines (24 loc) · 1.51 KB
Magic Method When it gets invoked (example) Explanation
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) +self Unary plus sign
neg(self) -self Unary minus sign
invert(self) ~self Bitwise 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 exist Accessing nonexistent attribute
setattr(self, name, val) self.name = val Assigning to an attribute
delattr(self, name) del self.name Deleting an attribute
getattribute(self, name) self.name Accessing any attribute
getitem(self, key) self[key] Accessing an item using an index
setitem(self, key, val) self[key] = val Assigning to an item using an index
delitem(self, key) del self[key] Deleting an item using an index
iter(self) for x in self Iteration
contains(self, value) value in self, value not in self Membership 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