• [^] # Re: Différence avec Python ?

    Posté par . En réponse à la dépêche Sortie de Ruby 1.8.2. Évalué à 3.

    Ruby
    class Rectangle
     include Comparable
     attr_reader :width, :height
     def initialize(w, h)
     @width, @height = w, h
     end
     def <=>(o)
     [@width, @height] <=> [o.width, o.height]
     end
    end
    class Square < Rectangle
     def initialize(side)
     @width = @height = side
     end
     def <=>(o)
     if o.type == Square
     @width <=> o.width
     else
     o <=> self
     end
     end
    end
    
    Python
    class Rectangle:
     def width(self):
     return self.__width
     def height(self):
     return self.__height
     def __init__(self, w, h):
     self._width, self.__height = w, h
     def __cmp__(self, o):
     return cmp(
     [self._width, self.__height],
     [o.width(), o.height()])
    class Square(Rectangle):
     def __init__(self, side):
     self._width = self.__height = side
     def __cmp__(self, o):
     if isinstance(o, Square):
     return cmp(self.__width, o.width())
     else:
     return o.__cmp__(self)
    
    Merci à Lucas pour l'exemple ;-)