property

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
from datetime import datetime
class Person(object):
def __init__(self, born):
self.born = born
@property
def age(self):
return self.__age
#def age(self):
#return self.__age
#age = property(age)
def _get_born(self):
return self.__born
def _set_born(self, born):
self.__born = born
self.__age = (datetime.now().year - born.year)
born = property(_get_born, _set_born)
>>> person = Person(datetime(1954, 1, 25))
>>> person.born
datetime.datetime(1954, 1, 25, 0, 0)
>>> person.age
54
>>> person.born = datetime(1968, 8, 31)
>>> person.age
40
>>> person.age = 16
---------------------------------------------------------------------------
<type 'exceptions.AttributeError'> Traceback (most recent call last)
C:\Documents and Settings\murkt\<ipython console> in <module>()
<type 'exceptions.AttributeError'>: can't set attribute
class C(object):
def __init__(self, x):
self.x = x
obj = C(5)
obj.x = 6 # set
print obj.x # get
class C(object):
def __init__(self, x):
self._x = x
def get_x(self):
return self._x
def set_x(self, x):
self._x = x
x = property(get_x, set_x)
obj = C(5)
obj.x = 6 # set
print obj.x # get
>>> print property.__doc__
property(fget=None, fset=None, fdel=None, doc=None) -> property
attribute
class C(object):
def getx(self): return self.__x
def setx(self, value): self.__x = value
def delx(self): del self.__x
x = property(getx, setx, delx, "I'm the 'x' property.")
import math
class triang(object):
sidea=0
sideb=0
sidec=0
def __init__(self,a,b,c):
self.sidea = a
self.sideb = b
self.sidec = c
def getArea(self):
s = 0.5 * (self.sidea + self.sideb + self.sidec)
ta = math.sqrt(s*(s-self.sidea)*(s-self.sideb)*(s-self.sidec))
return ta
def setArea(self,value):
s = 0.5 * (self.sidea + self.sideb + self.sidec)
raise AttributeError, "Area cannot be altered"
#http://users.rcn.com/python/download/Descriptor.htm