# # copying objects # # Matt Bishop, ECS 36A, Fall 2019 # import copy # dates class Date: def __init__(self, m=1, d=1, y=2019): self.month = m self.day = d self.year = y def __str__(self): return "%02d/%02d/%04d" % (self.month, self.day, self.year) # times class Time: def __init__(self, h=0, m=0, s=0): self.hour = h self.minute = m self.second = s def __str__(self): return "%02d:%02d:%02d" % (self.hour, self.minute, self.second) # date and time class When: def __init__(self, d, t): self.date = d self.time = t def __str__(self): return str(self.date) + " @ " + str(self.time) # # set up two set of dates and times # d1 = Date(3, 10, 2019) t1 = Time(15, 49, 12) d2 = Date(2, 18, 2001) t2 = Time(6, 14) # # show how = works # print("w1 = x") # set x and assign it x = When(d2, t2) w1 = x # print the values print("x =", x) print("w1 =", w1) # test for sameness of x, w1 print("w1 == x is", w1 == x, end=';') print(" w1.date == x.date is", w1.date == x.date, end=';') print(" w1.time == x.time is", w1.time == x.time) # test for sameness of w1 subobjects, x subobjects print("w1 is x", w1 is x, end=';') print(" w1.date is x.date is", w1.date is x.date, end=';') print(" w1.time is x.time is", w1.time is x.time) # now demonstrate it by assignments print("Now set w1's date and time") w1.date = d1 w1.time = t1 print("x =", x) print("w1 =", w1) print("------------------------") # # show how copy works # print("w2 = copy.copy(x)") # set x and copy it x = When(d2, t2) w2 = copy.copy(x) # print the values print("x =", x) print("w2 =", w2) # test for sameness of x, w2 print("w2 == x is", w2 == x, end=';') print(" w2.date == x.date is", w2.date == x.date, end=';') print(" w2.time == x.time is", w2.time == x.time) # test for sameness of w2 subobjects, x subobjects print("w2 is x", w2 is x, end=';') print(" w2.date is x.date is", w2.date is x.date, end=';') print(" w2.time is x.time is", w2.time is x.time) # now demonstrate it by assignments print("Now set w2's date and time") w2.date = d1 w2.time = t1 print("x =", x) print("w2 =", w2) print("------------------------") # # show how deepcopy works # print("w3 = copy.deepcopy(x)") # set x and (deep) copy it x = When(d2, t2) w3 = copy.deepcopy(x) # print the values print("x =", x) print("w3 =", w3) # test for sameness of x, w3 print("w3 == x is", w3 == x, end=';') print(" w3.date == x.date is", w3.date == x.date, end=';') print(" w3.time == x.time is", w3.time == x.time) # test for sameness of w3 subobjects, x subobjects print("w3 is x", w3 is x, end=';') print(" w3.date is x.date is", w3.date is x.date, end=';') print(" w3.time is x.time is", w3.time is x.time) # now demonstrate it by assignments print("Now set w3's date and time") w3.date = d1 w3.time = t1 print("x = ", x) print("w3 =", w3) print("d1", d1, "d2", d2, "t1", t1, "t2", t2)