Reputation: 153
My teacher told us to make a Clock
class that will take hours
, minutes
and seconds
as instance variables. He then gave us a bunch of different methods we had to make to complete objectives he gave us regarding the Clock
class.
One of our tasks was to implement a method called print12()
that prints out the time with colons and appends AM or PM to the end. He asked us to test it by entering print12(myclock)
. Mine only works if I enter myclock.print12()
. I'm not sure if he made an error or I implemented my code wrong.
Here is my code:
class Clock:
def __init__(self, hour, minute, second):
self.hour = hour
self.minute = minute
self.second = second
def __str__(self):
return '%02d'%self.hour+':'+'%02d'%self.minute+':'+'%02d'%self.second
def print12(self):
if self.hour >= 13:
print(self,"P.M.")
else:
print(self,"A.M.")
def advance(self,s1):
if s1 == 'sec':
self.second += 1
elif s1 == 'min':
self.minute += 1
elif s1 == 'hour':
self.hour += 1
if self.second == 60:
self.second = 0
self.minute += 1
if self.minute == 60:
self.minute = 0
self.hour += 1
if self.hour == 24:
self.hour = 0
self.minute = 0
self.second = 0
Here is his main code to test the program:
myclock = Clock(15,59,5)
print(myclock)
print12(myclock)
myclock.advance('sec')
print(myclock)
myclock.advance('min')
print(myclock)
This does not work for me but will work if I replace print12(myclock)
with myclock.print12()
.
Upvotes: 1
Views: 116
Reputation: 168596
Based solely on your reporting, the teacher likely meant one of two things:
1) Create a method of Clock
that prints as indicated:
class Clock:
...
def print12(self):
if self.hour >= 13:
print(self,"P.M.")
else:
print(self,"A.M.")
# Usage:
myclock=Clock(...)
myclock.print12()
2) Create a function, outside of Clock
, which takes a Clock
as an argument and prints as indicated:
class Clock:
...
def print12(clock):
if clock.hour >= 13:
print(clock,"P.M.")
else:
print(clock,"A.M.")
# Usage:
myclock = Clock(...)
print12(myclock)
You'll need to ask your instructor which he meant.
Upvotes: 2
Reputation: 4653
The print12
function is only defined inside the Clock
class, so it should be called on instances of that class. Hence, myclock.print12
is the proper way.
Upvotes: 2