Implement datetime module in Python OOP - python

I am trying to implement datetime module to my Clock OOP, but the data is not being updated with the current hour, minute and second. Please have a look at the code. I can't see what I am doing wrong.
import datetime
import time
# Python class to emulate CLock
class ClockNow2:
def __init__(self):
self.theHour = 0
self.theMinute = 0
self.theSecond = 0
self.theLocale ="Unknow"
self.AM = True
#setters and getters (transformers and accessors)
#one setter and getter for each attribute
def setHour(self):
self.theHour =datetime.timezone
def getHour(self):
return self.theHour
def setMinute(self):
self.theMinute = now.minute
def getMinute(self):
return self.theMinute
def setSecond(self):
self.theSecond = now.second
def getSecond(self):
return self.theSecond
def setLocale(self,newval):
self.theLocale = newval
def getLocale(self):
return self.theLocale
def toString(self):
clockstring = "The time in " +self.theLocale + " is " +str(self.theHour) \
+ ":" +str(self.theMinute) + ":" + str(self.theSecond)
return clockstring

Related

Countdown with Python and Gtk, problems with timeout_add

I'm trying to make a workout app, so I have to count each push-up or display a countdown for side plank. To do that I tried to use GObject.timeout_add but it appears it doesn't work like I thought it would.
In the current situation, all exercises of a session are run simultaneously, instead of one at a time, in the proper order.
I am certainly missing something, and through my web searching, I still haven't found it.
Here is my code :
#!/usr/bin/python
"""
Work out app to keep track of your progression through the session
"""
import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, Gdk, GObject
from Programms import *
from time import sleep
def time_hours(t):
return t // 3600
def time_minutes(t):
return (t % 3600) // 60
def time_seconds(t):
return int((t % 3600) % 60)
def time_format(t):
hours = double_digit(time_hours(t))
minutes = double_digit(time_minutes(t))
seconds = double_digit(time_seconds(t))
return "{}:{}:{}".format(hours, minutes, seconds)
def double_digit(t):
if t == 0:
return "00"
elif t < 10:
return "0{}".format(t)
return t
class StartingLine:
"""
Gtk
"""
def __init__(self):
# main window
self.window = Gtk.Window()
self.window.set_title("Work out !")
self.window.set_size_request(200, 200)
self.window.connect('destroy', lambda x: Gtk.main_quit())
# start button
self.button = Gtk.Button("Start")
self.button.connect('clicked', self.start_work_out)
self.window.add(self.button)
self.window.show_all()
def start_work_out(self, widget):
self.window.hide()
work = Two
duration = work.duration
for exo in work.exercises:
Instructor(exo, duration)
class Instructor:
"""
Gtk
"""
def __init__(self, exo, duration):
# main window
self.window = Gtk.Window()
self.window.set_title("Work out !")
self.window.set_size_request(200, 200)
self.window.connect("destroy", lambda x: Gtk.main_quit())
# timer
self.current_time = 0
self.counter = 0
self.timer_label = Gtk.Label(time_format(self.counter))
# exercise
self.current_exercise = Gtk.Label(exo.name)
# overall progression
self.bar = Gtk.ProgressBar.new()
# hierarchy
grid = Gtk.Grid()
grid.attach(self.timer_label, 1, 0, 1, 1)
grid.attach(self.current_exercise, 1, 1, 1, 1)
grid.attach(self.bar, 1, 2, 1, 1)
self.window.add(grid)
# display
self.window.show_all()
if exo.type == ExoType.Reps:
print('exercise : ', exo.name)
self.counter = 0
self.timer_label.set_label(str(self.counter))
rep_id = GObject.timeout_add(1000*exo.in_between, self.display_rep, exo, duration)
print("rep ID : ", rep_id)
elif exo.type == ExoType.Timer:
self.counter = exo.number
self.timer_label.set_label(time_format(self.counter))
time_id = GObject.timeout_add(1000*exo.in_between, self.display_timer, exo, duration)
print("time ID : ", time_id)
def display_rep(self, exo, duration):
print("current time : ", self.current_time)
print("current exercise : ", exo.name)
print("rep : ", self.counter)
self.counter += 1
self.current_time += exo.in_between
self.timer_label.set_label(str(self.counter)) # update counter
self.current_exercise.set_label(exo.name) # update exercise name
self.bar.set_fraction(self.current_time/duration) # update progression bar
return self.counter < exo.number
def display_timer(self, exo, duration):
print("current time : ", self.current_time)
print("current exercise : ", exo.name)
print("timer : ", self.counter)
self.counter -= 1
self.current_time += exo.in_between
self.timer_label.set_label(time_format(self.counter)) # update counter
self.current_exercise.set_label(exo.name) # update name
self.bar.set_fraction(self.current_time/duration) # update progression bar
return self.counter > 0
if __name__ == "__main__":
StartingLine()
Gtk.main()
In this code I have used two types, which are :
#!/usr/bin/python
"""
define class exercise and class session
"""
class Exercise:
def __init__(self, name, typo, unilateral, number, preparation=0, in_between=1):
"""
:param name: name of the exercise
:param typo: either timer or reps
:param number: either a time in seconds or a a number of reps
:param preparation: time allocated to prepare the exercise, to put yourself in position
:param in_between: time between reps. 1s by default.
"""
self.name = name
self.type = typo
self.unilateral = unilateral
self.number = number
self.prep = preparation
self.in_between = in_between
class ExoType(enumerate):
Reps = 0
Timer = 1
class Session:
def __init__(self, name, exercises):
self.name = name
self.exercises = exercises
self.duration = time_length(exercises)
def time_length(exercises):
t = 0
for exo in exercises:
if exo.type == ExoType.Timer:
t += exo.number
elif exo.type == ExoType.Reps:
t += exo.number*exo.in_between
else:
print("Error : Session duration")
return t
First time I ask a question here, please tell me if I'm doing wrong.
rep_id = GObject.timeout_add(1000*exo.in_between, self.display_rep, exo, duration)
When you timeout_add you tell Mainloop to call function every n seconds.
for exo in work.exercises:
Instructor(exo, duration)
Here you add every exercise to mainloop, which leads to simultaneous run, because you create mainloop once.
There are several solutions and in my opinion none of them includes main_iteration_do.
Reorganise things so that 1 exercise runs it's own mainloop.
Emit a signal when one exercise is finished and in it's handler start another exercise.

Initializing Class instance within a class

the entire counter list of methods in side counter class do not work. I want setcap to set of cap, and check cap to see if each counter have reached their limit as hr min sec are what a clock should know i would like to initialize them inside the clock.
import time
class counter():
count = 0
cap = 0
def _init_(self):pass
def reset(self):
self.count = 0
def increment(self):
self.count += 1
def setcap(self,x):
print x
self.cap = x
def checkcap(self):
if self.cap > self.count:
return False
else:
return True
class clock():
_hr = counter()
_min = counter()
_sec = counter()
def _init_(self):
self._hr.setcap(23)
self._min.setcap(59)
self._sec.setcap(59)
def manualreset(self):
self._hr.reset()
self._min.reset()
self_sec.reset()
def tick(self):
if self._sec.checkcap():
self._sec.reset()
self._min.increment()
if self._min.checkcap():
self._min.reset()
self._hr.increment()
if self._hr.checkcap():
self._hr.reset()
else:
self._sec.increment()
newClock = clock()
raw_input("Press enter to start clock")
while newClock._hr != 24:
newClock.tick()
print str(newClock._hr.count).zfill(2) + str(newClock._min.count).zfill(2) + str(newClock._sec.count).zfill(2)
One of the problems in your code is that your init functions are init.
Try using
def __init__(self):
pass
This should solve one of your problems

Stopwatch implementing python

I got this code for an assignment:
from stop_watch import StopWatch
size = 1000000
stopWatch = StopWatch()
sum = 0
for i in range(1, size + 1):
sum += i
stopWatch.stop()
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")
I have to create a class which generates a stopwatch and this is my code:
import time
class StopWatch:
def __init__(self):
pass
def start(self):
self.start = time.time()
return self.start
def stop(self):
self.stop = time.time()
return self.stop
def get_elapsed_time(self):
print(str(self.stop-self.start))
I get this error:
File "week33.py", line 10, in <module>
print("The loop time is", stopWatch.get_elapsed_time(), "milliseconds")
File "/Users/Marinkton/Desktop/stop_watch.py", line 16, in get_elapsed_time
print(str(self.stop-self.start))
TypeError: unsupported operand type(s) for -: 'float' and 'method'
What am I doing wrong? I could not discover a mistake.
You can't name your functions and your properties the same thing. When you do self.stop = time.time(), you overwrite the function stop.
You need to change the name of the internal fields.
import time
class StopWatch:
def __init__(self):
self.start_time = 0
self.stop_time = 0
def start(self):
self.start_time = time.time()
return self.start_time
def stop(self):
self.stop_time = time.time()
return self.stop_time
def get_elapsed_time(self):
print(str(self.stop_time - self.start_time))
PS: You're never calling start in your code.

Python, How to use part of function outside function

How can I use today and returntime in return_fee function?
import datetime
class Movie(object):
def __init__(self,title):
self.title = title
def time_of_return(self):
self.today = today
self.returntime = returntime
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = -2
delta = today - returntime
I would do it like this:
class Movie(object):
def __init__(self,title):
self.title = title
def get_times(self):
now = datetime.datetime.now()
return now, now + datetime.timedelta(days=30)
def time_of_return(self):
now, returntime = self.get_times()
return returntime
def return_fee(self):
fee = -2
now, returntime = self.get_times()
delta = now - returntime
return <whatever based on fee and delta>
If you want time_of_return and return_fee to be instance attributes, call time_of_return from __init__ to set them and then prefix with self:
class Movie(object):
def __init__(self,title):
self.title = title
self.time_of_return()
def time_of_return(self):
self.today = datetime.datetime.now()
self.returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = None
delta = self.today - self.returntime
# ... presumably do something else
Alternatively (since, in particular, today may change over time), call the function time_of_return from within return_fee and make sure it returns something:
class Movie(object):
def __init__(self,title):
self.title = title
def time_of_return(self):
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
return today, returntime
def return_fee(Movie):
fee = None
today, returntime = self.time_of_return()
delta = today - returntime
# ... presumably do something else
It's a good idea to indent your code by 4 spaces, by the way. And None (or 0) would be a better default value for fee.
class Movie(object):
def __init__(self,title,today,returntime):#<----
self.title = title
def time_of_return(self):
self.today = today
self.returntime = returntime
today = datetime.datetime.now()
returntime = today + datetime.timedelta(days=30)
def return_fee(Movie):
fee = -2
delta = today - returntime
That's because __init__() is taking arguments that using for class from outside.But, when you use your Movie class, you have to define that arguments.

Python Property, How do I get this to work correctly

I am trying to use OO on python to create a nice structured class. I have an object that all functions from one class will inherit but there are sub functions (getter and setter) that may require one or two additional parameters.
How can I get this type of logic to work correctly.
class XYZ(object):
def __init__(self, cameraId):
self.cameraId = cameraId;
self.index = "";
def get_test(self):
print "Index: " + self.index + " CameraID: " + self.cameraId;
return self.cameraId;
def set_test(self, value, myValue=""):
self.cameraId = value;
self.index = myValue;
return True;
TEST_XYZ = property(get_test,set_test);
You can use tuple-typed values. Note that you don't have to use ; after your statements...
class XYZ(object):
def __init__(self, cameraId):
self.cameraId = cameraId
self.index = ""
def get_test(self):
print "Index: " + self.index + " CameraID: " + self.cameraId
return self.cameraId
def set_test(self, value):
# Require value to be a tuple!
assert(isinstance(value, tuple))
self.cameraId = value[0]
try:
self.index = value[1]
except IndexError:
self.index = ""
return True
TEST_XYZ = property(get_test, set_test)

Categories

Resources