יום שישי, 31 במאי 2013

Play with Payton collections

Derived my class from dict and overriding the __missing__ method used to return value in case the key is not in the collection.

  1: class myTestCls (dict):
  2:     def __missing__ (self, key):
  3:         return "Not here sory"
  4: theCls = myTestCls();
  5: 
  6: print ( theCls["TestValue"])
  7: 
  8: print (" -- done --") 
  9: 
 10: 

Check if the new type collection is equal to base collection with the same values


  1: class myTestCls (dict):
  2:     def __missing__ (self, key):
  3:         return "Not here sory"
  4: 
  5: theCls1 = myTestCls(cat=1, dog=2, pig=3)
  6: 
  7: theCls2 = {'cat': 1, 'dog': 2, 'pig': 3} 
  8: 
  9: print ( theCls1 == theCls2)
 10: 
 11: print ( type ( theCls1))
 12: 
 13: print ( type ( theCls2))
 14: 
 15: print (" -- done --") 
 16: 

The results
True
<class '__main__.myTestCls'>
<class 'dict'>


Override the __eq__ method in order to check that the types of the objects are the same.


  1: class myTestCls (dict):
  2:     def __missing__ (self, key):
  3:         return "Not here sory"
  4:     def __eq__(self, other):
  5:         if type (other) == type( self):
  6:             return super(myTestCls, self).__eq__( other)
  7:         return False
  8:         
  9:     def __ne__(self, other):
 10:         return NotImplemented
 11: 
 12: theCls1 = myTestCls(cat=1, dog=2, pig=3)
 13: 
 14: theCls2 = {'cat': 1, 'dog': 2, 'pig': 3} 
 15: 
 16: theCls3 = myTestCls(zip (['cat', 'dog', 'pig'], [1, 2, 3]))
 17: 
 18: print ( theCls1 == theCls2)
 19: 
 20: print ( theCls1 == theCls3)
 21: 
 22: print ( type ( theCls1))
 23: 
 24: print ( type ( theCls2))
 25: 
 26: print ( type ( theCls3))
 27: 
 28: print (" -- done –")

returns
False
True
<class '__main__.myTestCls'>
<class 'dict'>
<class '__main__.myTestCls'>


http://docs.python.org/3.3/library/stdtypes.html#set

אין תגובות:

הוסף רשומת תגובה