Python-Ref > Object oriented programming > Basics > Properties
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Properties

Attributes that have methods working behind the scenes.
In new versions of python it is possible to create so called properties that represent a kind of controled attributes.
Properties are using access methods behind the scenes but present themselves as normal properties to the outside world. This combines the natural way of directly accessing attributes with the safety of using access methods.
To use properties object must be derived from the class "object". The following code shows how the properties are implemented.
Expand/Shrink
Zdroj: (oop8-1.py)
  1   class Rectangle( object):
  2   
  3     def __init__( self, width, height):
  4       self.width = width
  5       self.height = height
  6   
  7     def _setWidth( self, width):
  8       self._width = width
  9       print "width changed to", width
 10   
 11     def _getWidth( self):
 12       return self._width
 13   
 14     width = property( _getWidth, _setWidth)
 15   
 16     def _setHeight( self, height):
 17       self._height = height
 18       print "height changed to", height
 19       
 20     def _getHeight( self):
 21       return self._height
 22   
 23     height = property( _getHeight, _setHeight)
 24   
 25     def _getArea( self):
 26       return self.width * self.height
 27   
 28     area = property( _getArea, None) # read only property
 29   
 30   r1 = Rectangle( 3, 2)
 31   r1.width = 1
 32   r1.height = 4
 33   print r1.area
stdout:
width changed to 3
height changed to 2
width changed to 1
height changed to 4
4
Doba běhu: 21.7 ms