Last active
June 15, 2020 19:15
-
-
Save stkrp/8247f6b986405a2ca094ea9026fde639 to your computer and use it in GitHub Desktop.
Least and greatest objects in python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class _Singleton(type): | |
_instances = {} | |
def __call__(cls, *pargs, **kwargs): | |
mcls = cls.__class__ | |
if cls not in mcls._instances: | |
mcls._instances[cls] = super().__call__(*pargs, **kwargs) | |
return mcls._instances[cls] | |
class Least(metaclass=_Singleton): | |
""" | |
The type of objects that are smaller than the others. It is used to sort | |
the elements of different types, replacing the incomparable types. | |
>>> sorted( | |
... [1, 2, 3, None, 3, 2, 1, 4, 5, None, 6], | |
... key=lambda num: num if isinstance(num, (int, float)) else Least() | |
... ) | |
[None, None, 1, 1, 2, 2, 3, 3, 4, 5, 6] | |
""" | |
def __lt__(self, other): | |
return True | |
def __gt__(self, other): | |
return not self.__lt__(other) | |
class Greatest(metaclass=_Singleton): | |
""" | |
The type of objects that are greater than the others. It is used to sort | |
the elements of different types, replacing the incomparable types. | |
>>> sorted( | |
... [1, 2, 3, None, 3, 2, 1, 4, 5, None, 6], | |
... key=lambda num: num if isinstance(num, (int, float)) else Greatest() | |
... ) | |
[1, 1, 2, 2, 3, 3, 4, 5, 6, None, None] | |
""" | |
def __gt__(self, other): | |
return True | |
def __lt__(self, other): | |
return not self.__gt__(other) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Можно переделать в Singleton.
В любом случае нужно сделать, чтобы все экземпляры были равны между собой.