[NAME]
ALL.misc.comparison.overloading

[TITLE]
Operator Overloading (Python)

[DESCRIPTION]

This help entry will demonstrate a few examples to compare Dao and Python in operator ov
erloading for field accessing, subindexing and binary operator etc.

 0.1   Field Getter and Setter  

     
   1  # Python
   2  class Something:
   3      def __init__(self):
   4          self.thing = {}
   5  
   6      def __getattr__(self, name):
   7          if name == "something":
   8              return self.thing
   9          return None
  10  
  11      def __setattr__(self, name, value):
  12          if name == "something":
  13              self.thing = value;
     

     
   1  # Dao
   2  class Something
   3  {
   4      var thing = {}
   5  
   6      routine .something() {
   7          return thing
   8      }
   9      routine .something=( value ){
  10          thing = value;
  11      }
  12  }
     

Or alternatively in Dao, 
     
   1  # Dao
   2  class Something
   3  {
   4      var thing = {}
   5  
   6      routine .( name : string ) {
   7          if( name == "something" ) return thing
   8          return none;
   9      }
  10      routine .=( name : string, value ){
  11          if( name == "something" ) thing = value;
  12      }
  13  }
     


 0.2   Item Getter and Setter  

     
   1  # Python
   2  class UserDict:
   3      def __init__(self):
   4          self.data = {}
   5  
   6      def __getitem__(self, key):
   7          return self.data[key]
   8  
   9      def __setitem__(self, key, item):
  10          self.data[key] = item
     

     
   1  # Dao
   2  class UserDict
   3  {
   4      var data = {=>}
   5  
   6      routine []( key ){
   7          return data[key]
   8      }
   9      routine []=( item, key ){
  10          data[key] = item
  11      }
  12  }
     
Please note that in routine[]=, item is the first parameter. It is arranged in this way t
o naturally support multiple keys/indices. For example, for a multidimensional array, one
may define, 
     
   1  class UserMatrix
   2  {
   3      var data = []
   4  
   5      routine UserArray( N: int, M: int ){
   6          data = array<int>(N,M){ [index] index }
   7      }
   8  
   9      routine []( index1, index2 ){
  10          return data[ index1, index2 ]
  11      }
  12      routine []=( item, index1, index2 ){
  13          data[ index1, index2 ] = item
  14      }
  15  }
     


 0.3   Arithmetic Operators  

     
   1  # Python
   2  class MyNumber:
   3  
   4      def __init__(self, value):
   5          self.value = value
   6  
   7      def __add__(self, other):
   8          return MyNumber( self.value + other.value )
     

     
   1  # Dao
   2  class MyNumber
   3  {
   4      var value = 0
   5  
   6      routine MyNumber( value = 0 ) {
   7          self.value = value
   8      }
   9  
  10      routine +( other: MyNumber ) {
  11          return MyNumber( value + other.value )
  12      }
  13  }