SHARE
TWEET

Python - classes - Train, Wagon

furas Jul 13th, 2018 82 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. class Wagon():
  2.    
  3.     def __init__(self, mass=0):
  4.         self.mass = mass
  5.        
  6.     def __add__(self, other):
  7.         tr = Train()
  8.         tr += self
  9.         tr += other
  10.         return tr
  11.  
  12.     def __str__(self):
  13.         return str(self.mass)
  14.  
  15.     def __repr__(self):
  16.         return str(self.mass)
  17.  
  18. class Train():
  19.    
  20.     def __init__(self):
  21.         self.wagons = []
  22.         self.mass = 0
  23.        
  24.     def __add__(self, other):
  25.         self.wagons.append(other)
  26.         self.mass += other.mass
  27.         return self
  28.  
  29. # ----------------------------------
  30.  
  31. train1 = Wagon(1) + Wagon(2)
  32.  
  33. train1 += Wagon(3)
  34.  
  35. print(train1.mass) # 6
  36. print(train1.wagons) # [1,2,3]
  37.  
  38. train2 = Wagon(21) + Wagon(23) + Wagon(33)
  39.  
  40. print(train2.mass) # 77
  41. print(train2.wagons) # [21, 23, 33]
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