I am trying to create a schedule class in python that takes the start time, end time, and location of a meeting. So far I have:
class Schedule(Time):
def __init__(self, start_time, end_time, location):
self.start_time = start_time
self.end_time = end_time
self.location = location
print (self.start_time)
print (self.end_time)
print (self.location)
I have a Time class completed which looks like this:
class Time():
def __init__(self, init_hr = 12, init_min = 0, init_ampm = "AM"):
self.hr = init_hr
self.min = init_min
self.ampm = init_ampm
Now I want to be able to make the parameters start_time and end_time (from the initialization of schedule) to be Time instances, however I’m confused on how I would go about doing that. Any suggestions?
Some dynamically-typed languages would want you to do this everywhere (statically-typed languages will generally enforce it themselves), but in Python the generally recommended practice is duck typing, which suggests that you just expect it to be a Time, but if it’s something else, don’t worry (if it implements the same interface as Time, well and good, if it doesn’t, let it fail when you try accessing attributes that don’t exist on the object). The general idea there is that you are expected to be intelligent enough to know what you’re doing.
If a I were writing this code, I would leave it as you have it, with a few notes:
class Schedule(Time)toclass Schedule(object).Time.__init__, don’t call your parametersinit_hr, etc., just call themhr, etc. Python ain’t Java, where you’ve got to use different names or always refer to the class version asthis.*. In Python, you always useself.*. Python also has keyword arguments – so you could haveTime(hr=4, ...);Time(init_hr=4, ...)would be ugly.print (...)toprint .... If you’re in Python 3, change it toprint(...).