Exemple de définition d'une classe en Python

Python est un langage de programmation orienté objets. Il est donc possible de définir des nouveaux types de données par le biais de classe.

Exemple de code

#!/usr/bin/python3
                                
class RationalException(BaseException):
    
    def __init__( self, message ):
        self.__message = message

    def getMessage(self): 
        return self.__message
        
        

class Rational:
    
    # Un constructeur
    def __init__( self, numerator = 0, denominator = 1 ):
        self.setNumerator(numerator)
        self.setDenominator(denominator)
        self.simplify()

    #getters and setters
    def getNumerator(self):
        return self.__numerator
    
    def setNumerator(self, numerator):
        self.__numerator = numerator
        
    def getDenominator(self):
        return self.__denominator
    
    def setDenominator(self, denominator):
        if denominator == 0:
            raise RationalException( "Denominateur cannot be null" )
        self.__denominator = denominator

    numerator = property( getNumerator, setNumerator )
    denominator = property( getDenominator, setDenominator )

    # Quelques méthodes de manipulation de nombres rationnels
    def simplify(self):
        currentDivider = 2
        while currentDivider <= min( self.__numerator, self.__denominator ):
            if self.__numerator % currentDivider == 0 and self.__denominator % currentDivider == 0:
                self.__numerator /= currentDivider
                self.__denominator /= currentDivider
            else:
                currentDivider += 1 
        
        
    def __add__(self, other):
        newNum = self.__numerator * other.__denominator \
               + self.__denominator * other.__numerator
        newDen = self.__denominator * other.__denominator
        r = Rational( newNum, newDen )
        r.simplify()
        return r
    
    def toFloat(self):
        return self.__numerator / self.__denominator
        
    # calcule de la chaine de representation de l'objet
    def __str__(self):
        return "[%d/%d]" % (self.__numerator, self.__denominator)
    
   
    
# Jeu de tests sur nos nombres rationnels
if __name__ == '__main__':
    r1 = Rational(1, 2)
    print( "r1 == " + str( r1 ) )
    
    
    r2 = Rational(4,1)
    print( "r2 == " + str( r2 ) )
    
    r = r1 + r2
    print( "%s + %s == %s" % (r1, r2, r) )
    
    rToSimplify = Rational( 100, 50 )
    print( "[100,50] == %s" % ( rToSimplify ) )

    r = Rational()
    r.numerator = 33;
    r.denominator = 44;
    print( "Prop: %s" % str(r) )

    try:
        rBad = Rational( 0, 0 )
    except RationalException as e:
        print( "Error >>> %s" % ( e.getMessage() ) )

Pour lancer cet exemple, veuillez procéder ainsi :

$> python3 Rational.py 
r1 == [1/2]
r2 == [4/1]
[1/2] + [4/1] == [9/2]
[100,50] == [2/1]
Prop: [33/44]
Error >>> Denominateur cannot be null
$>