• # class property

    Posté par . En réponse au journal [MyFirstPython, nouveau projet ?]Le python c'est bien mangez-en !!. Évalué à 1.

    Pour avoir un "vrai" typage, ça va être dur directement, car tu peut toujours faire du "a = quelquechose" qui va t'effacer l'ancien a, quoiqu'il arrive.

    Le moyen le plus simple est d'utiliser les property des classes:

    class Tint(object):
     def __init__(self, val):
     self.data = val
     @property
     def data(self):
     return self._data
     @data.setter
     def data(self,val):
     if type(val) is int:
     self._data = val
     else:
     raise TypeError("Donne un entier")
    >>> a =Tint(3)
    >>> print a.data
    3
    >>> a.data = 4
    >>> print a.data
    4
    >>> a.data = 4.1
    (...)
    TypeError: Donne un entier
    >>> a.data += 3
    >>> print a.data
    7
    >>> a.data += 4.2
    (...)
    TypeError: Donne un entier
    >>> a.data += "toto"
    TypeError: unsupported operand type(s) for +=: 'int' and 'str'
    >>> b = Tint(3.2)
    TypeError: Donne un entier
    
    

    Pas parfait, mais surement le plus simple.