יום רביעי, 5 ביוני 2013

python properties setter getter and deleter

Property attribute allows to declare read only attribute using the @property attribute.
For an example:

  1: class myCls():
  2:     def __init__(self):
  3:         pass 
  4:         self.myPropValue = 164
  5:     @property
  6:     def ProoValue(self):
  7:         return self.myPropValue
  8: 
  9: theCls = myCls()
 10: 
 11: print (theCls.ProoValue)
 12: 
 13: print ("Done")

Declaring a full property in python is done using properties setter and getter  and deleter attributes.
Note that the property should be declare using the @property attribute in front  of the setter and getter declarations.


  1: class myCls():
  2:     def __init__(self):
  3:         pass 
  4:         self.myPropValue = 164
  5:     @property
  6:     def ProoValue(self):
  7:         return self.myPropValue
  8: 
  9:     @ProoValue.setter
 10:     def ProoValue(self, value):
 11:         self.myPropValue = value
 12: 
 13:     @ProoValue.deleter
 14:     def ProoValue(self):
 15:         del self.myPropValue
 16: 
 17: theCls = myCls()
 18: 
 19: theCls.ProoValue = 6
 20: 
 21: print (theCls.ProoValue)
 22: 
 23: del theCls.ProoValue
 24: 
 25: print ("Done")

אין תגובות:

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