Thing.py (1164B)
1 #!/usr/bin/env python3 2 # File : Thing.py 3 # Description: `Thing` class to study basic OOP design 4 # Copyright 2022 Harvard University. All Rights Reserved. 5 6 class Thing: 7 """Simple class for a 'thing'""" 8 def __init__(self, thing): 9 self.state = thing 10 11 def __str__(self): 12 return f"{self.state}" 13 14 def __add__(self, other): 15 """This method implements addition '+'""" 16 print(self.state) 17 return Thing(f"{str(self)} + {str(other)}") 18 19 def __iadd__(self, other): 20 """This method implements augmented addition assignment '+='""" 21 print(self.state) 22 self.state = f"{str(self)} + {str(other)}" 23 return self 24 25 26 def mutate(x): 27 y = Thing('B') 28 x += y # calls __iadd__: study line 23 29 return x 30 31 32 def rebind(x): 33 y = Thing('C') 34 x = x + y # calls __add__: study line 17 35 return x 36 37 38 if __name__ == "__main__": 39 A = Thing('A') 40 B = mutate(A) # after this function call A and B are the same object 41 C = rebind(A) # after this function call A and C are two different objects 42 print(f"id(A) = {id(A)}") 43 print(f"id(B) = {id(B)}") 44 print(f"id(C) = {id(C)}")