Python Magic Method of class¶
Overview¶
The magic method are a set of special methods that are invoked by specific actions in Python. They are often referred to as "dunder" methods because of the double underscore prefix and suffix. These methods provide a way to customize the behavior of objects when certain operations are performed on them. For example, the add() method is invoked when the + operator is used on an object, and the init() method is invoked when an object is created. By using magic methods, developers can create objects that behave in a more intuitive and natural way.
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