Advertisement
rfmonk

operator_classes.py

Jan 16th, 2014
108
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.66 KB | None | 0 0
  1. #!/usr/bin/env python
  2.  
  3.  
  4. from operator import *
  5.  
  6.  
  7. class MyObj(object):
  8.     """Example for operator overloading"""
  9.     def __init__(self, val):
  10.         super(MyObj, self).__init__()
  11.         self.val = val
  12.         return
  13.  
  14.     def __str__(self):
  15.         return 'MyObj(%s)' % self.val
  16.  
  17.     def __lt__(self, other):
  18.         """compare for less-than"""
  19.         print 'Testing %s < %s' % (self, other)
  20.         return self.val < other.val
  21.  
  22.     def __add__(self, other):
  23.         """add values"""
  24.         print 'Adding %s + %s' % (self, other)
  25.         return MyObj(self.val + other.val)
  26.  
  27. a = MyObj(1)
  28. b = MyObj(2)
  29.  
  30. print 'Comparison:'
  31. print lt(a, b)
  32.  
  33. print '\nArithmetic:'
  34. print add(a, b)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement