Skip to content

Instantly share code, notes, and snippets.

@JustinSDK
Created July 18, 2016 08:43
Show Gist options
  • Save JustinSDK/3f393980b3de55c54712f0c323595dc5 to your computer and use it in GitHub Desktop.
Save JustinSDK/3f393980b3de55c54712f0c323595dc5 to your computer and use it in GitHub Desktop.
Python - High Order Components?
def total_ordering(eq, gt):
def inner(clz):
class Ordering:
def __init__(self, *arg1, **arg2):
clz.__init__(self, *arg1, **arg2)
def __eq__(self, other):
return eq(self, other)
def __gt__(self, other):
return gt(self, other)
def __ge__(self, other):
return self > other or self == other
def __lt__(self, other):
return not (self > other and self == other)
def __le__(self, other):
return (not self >= other) or self == other
def __ne__(self, other):
return not self == other
def __getattr__(self, name):
def _missing(*args, **kwargs):
clz.__dict__[name](self, *args, **kwargs)
return _missing
return Ordering
return inner
@total_ordering(
lambda self, other: hasattr(other, 'radius') and self.radius == other.radius,
lambda self, other: hasattr(other, 'radius') and self.radius > other.radius
)
class Ball:
def __init__(self, radius):
self.radius = radius
def test(self):
print(self.radius, 'XD')
b1 = Ball(10)
b2 = Ball(20)
print(b1 > b2)
print(b1 <= b2)
print(b1 == b2)
b1.test()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment