# this piece of code tries to dynamically add math operations # such as addition (overloading the + operator using __add__) to an Integer class def testSetattr(funcName): # acts like a int but reports on operations class Integer(object): def __init__(self, num): self._int = num def __repr__(self): return '({})'.format(self._int) # makes a wrapper for integer operations def makeFunctionality(funcName): def wrapper(self, other): # print 'running function with two arguments: {}({}, {})'.format(funcName, self, other) return Integer(self._int.__getattribute__(funcName)(other._int)) return wrapper type.__setattr__(Integer, funcName, makeFunctionality(funcName)) a = Integer(2) b = Integer(3) print id(funcName), print ' a.__add__(b)=', a.__add__(b), print ' a+b=', a+b funcName1 = '__add__' funcName2 = '__%s__' % 'add' funcName3 = '__{}__'.format('add') import sys print sys.version print 'are all the strings the same? ' + str(funcName1 == funcName2 == funcName3) testSetattr(funcName1) testSetattr(funcName2) testSetattr(funcName3)