SHARE
TWEET

Untitled

a guest Apr 21st, 2019 76 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # To make python classes more powerful we should implement "rich comparisons".
  2. # Hashes are another dunder method which can be useful when creating many 'generic' objects
  3.  
  4. class Car:
  5.      def __init__(self, make: str, model: str, hp: int):
  6.         self.make = make
  7.         self.model = model
  8.         self.hp = hp
  9.  
  10.     def __repr__(self):
  11.         return f"A {self.make} {self.model} with {self.hp} horsepower"
  12.  
  13.     def __hash__(self):
  14.         return hash(tuple(self.__dict__.values()))
  15.      
  16.     def __eq__(self, other):    
  17.         return (self.make, self.model, self.hp) == (other.make, other.model, other.hp)
  18.  
  19.     def __lt__(self, other):
  20.         return self.hp < other.hp
  21.    
  22.     def __le__(self, other):
  23.         return self.hp <= other.hp
  24.      
  25.     def __gt__(self, other):
  26.         return self.hp > other.hp
  27.      
  28.     def __ge__(self, other):
  29.         return self.hp >= other.hp
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top