Skip to content

Python Magic Method of class

Short summary:

To customize the behavior of the greather than or equal to operator x >= y, override the ge() dunder method in your class definition. Python internally calls x.ge(y) to obtain a return value when comparing two objects using x >= y. The return value can be any data type because any value can automatically converted to a Boolean by using the bool() built-in function. If the ge() method is not defined, Python will raise a TypeError. Syntax ge(self, other) To use the greater than or equal to operator on custom objects, define the ge() "dunder" magic method that takes two arguments: self and other. You can then use attributes of the custom objects to determine if one is greater than or equal to the other.

The method should return a Boolean True or False — however, this is not required because every object can be automatically converted to a Boolean value using the built-in bool() function.

The full list of supported magic methods is:

hash, sizeof, repr and str

dir, format and subclasses

round, floor, trunc and ceil

Comparisons: lt, gt, le, ge, eq and ne

Container methods: getitem, setitem, delitem, contains, len, iter, reversed and missing

Context manager: enter, exit, aenter and aexit

Unary numeric methods: neg, pos and invert

The numeric methods (including right hand and in-place variants): add, sub, mul, matmul, truediv, floordiv, mod, divmod, lshift, rshift, and, xor, or, and pow

Numeric conversion methods: complex, int, float and index

Descriptor methods: get, set and delete

Pickling: reduce, reduce_ex, getinitargs, getnewargs, getstate and setstate

File system path representation: fspath

Asynchronous iteration methods: aiter and anext

Reference

Get from https://docs.python.org/3/library/unittest.mock.html

https://blog.finxter.com/python-__ge__-magic-method/