jeudi 8 octobre 2009

Définition des propriétés en Python

Petit exemple montrant la définition des propriétés dans les classes Pyhton (les classes New-Styles dérivant explicitement de "object")

>>> class Car(object):
      def __init__(self):
         self._im = '%s' % id(self)
         self._changed = False
      def _getim( self ):
         return self._im
      def _setim( self, value ):
         if value != self._im:
            self._im = value
            self._changed = True
      def _getchanged( self ):
         return self._changed
      immatriculation = property( _getim, _setim, None )
      hasChanged = property( _getchanged, None, None )
>>> Cars = dict()
>>> Cars['domeu']= Car()
>>> Cars['frc']= Car()
>>> # can also be written as follow
>>> # Cars = dict( (('domeu', Car()), ('frc', Car())) )
>>> for key, value in Cars.items():
      print( 'Car of %s with immatriculation "%s". Changed? %s.' % (key,value.immatriculation, value.hasChanged) )

Car of frc with immatriculation "18698568". Changed? False.
Car of domeu with immatriculation "18511832". Changed? False.
>>> 
>>> Cars['domeu'].immatriculation = 'XYZ 103'
>>> for key, value in Cars.items():
      print( 'Car of %s with immatriculation "%s". Changed? %s.' % (key,value.immatriculation, value.hasChanged) )


Car of frc with immatriculation "18668880". Changed? False.
Car of domeu with immatriculation "XYZ 103". Changed? True. 

Aucun commentaire: