Call a variable in one function from another function inside a class - python

I am following this answer and trying to call a variable of one function from another function, but getting an error. Below is my test code.
import datetime
from datetime import timedelta
import time
class TimeTesting:
def TimeTest1(self):
T1 = datetime.datetime.now()
time.sleep(5)
print('TimeTest1 is being called')
def TimeTest2(self):
T2 = datetime.datetime.now()
TimeDiff = T2 - self.T1
print('Timetest2 has been called')
print('Time diff is {}'.format(TimeDiff))
ob = TimeTesting()
ob.TimeTest1()
ob.TimeTest2()
Below is the error that I am getting -
TimeDiff = T2 - self.T1 AttributeError: 'TimeTesting' object has no
attribute 'T1'
Can someone point me out what I am doing wrong?

You would need to define T1 as an instance variable:
self.T1 = datetime.datetime.now()
As it stands, T1 is just a local variable to method TimeTest1, and is only in scope in that method.

Related

Python - How to update datetime.now()

When I call on datetime.now() in my program it calls the current time, but when I call it again, it displays the previous time. How can I update datetime.now() so it calls the current time eachtime?
You say:
but when I call it again
... but you're NOT calling it again. You're more-than-likely printing/outputting the value of the variable that the first datetime.now() was assigned to.
Let's say you have the following:
from datetime import datetime
first_time = str(datetime.now())
print('First datetime.now() value: %s' % first_time)
You're probably attempting to get the updated time by simply printing first_time (what you incorrectly refer to as "calling").
Instead, you should either overwrite first_time by reassigning datetime.now() to it, or you should declare a new variable and assign datetime.now() to it.
# Overwriting & outputting:
# first_time = datetime.now()
# Declaring a new (updated) value (what I'll use in the example):
second_time = datetime.now()
# Outputting:
print('first_time: %s\nsecond_time: %s' % (str(first_time), str(second_time)))
You can define as follows:
def now():
return datetime.datetime.now().strftime('%d.%m.%Y %H:%M:%S')
use the definition in the following way:
print('{}'.format(now()))

Python 3.xx : Classes in classes

I need help for my python scripts. How to access my clock's function through Date's classes ?
from datetime import date
from datetime import datetime
class Date(object):
def date_today(self):
now = date.today()
print (now)
class Time(Date):
pass
def clock(self):
hr = datetime.now()
hr_now = hr.hour
print (hr_now)
cr_date = Date()
print (cr_date.date_today())
print (cr_date.date_today.clock())
i got an error --> AttributeError: 'function' object has no attribute 'clock'. What is the reason for this error?
you can also add minute, second and other related functions in your time class. I hope it will help.
from datetime import date
from datetime import datetime
class Time():
def clock(self):
hr = datetime.now()
hr_now = hr.hour
return hr_now
class Date():
def __init__(self):
self.time = Time()
def date_today(self):
now = date.today()
return now
def clock(self):
return self.time.clock()
cr_date = Date()
print(cr_date.date_today())
print(cr_date.clock())

Python - Check if variable was given to function or was used the default one

I have a function that uses a datetime object as default value:
from datetime import datetime, timedelta
from random import randint
def getTime(date = datetime.now()):
i = randint(1,300)
date = date - timedelta(seconds = i)
return date
Now, I need to check if the date variable inside the function was given by another function or was used the default one datetime.now(). If was used the default one, then subtract i seconds, else return the date that was given.
You can do it as follows:
def my_function(date=None):
if date is None:
# The default is used
date = datetime.now()
...
Assuming that you want "now" to be computed every time:
def getTime(date=None):
return date or datetime.now() - timedelta(seconds=randint(1,300))
Otherwise:
Introduce a default arg:
def getTime(date=None, _default=datetime.now()):
return date or _default - timedelta(seconds=randint(1,300))
Or create a decorator:
def just_return_if_provided(f):
def inner(date=None):
return date or f(date)
return inner
#just_return_if_provided
def getTime(date=datetime.now()):
return date - timedelta(seconds=randint(1,300))

Function as argument in python

I need to pass some function as argument in another function. So, I want to add current time to class attribute every second, for example
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(input_function,args):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
input_function(args)
time.sleep(1)
measurement = Measurement()
smart_delay(measurement.add_value,time.time())
Ok, but after checking contents of measurement.values, I get
[1425980407.173, 1425980407.173, 1425980407.173, 1425980407.173] - so values are the same!!!
What happened? And how to get proper values?
Updated:
Actually, this question is about the way to allow to call some function, passed as the argument to another function. What do you think about this:
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(input_function):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
input_function()
time.sleep(1)
measurement = Measurement()
smart_delay(lambda: measurement.add_value(time.time()))
Your call to time.time() is executed before the call to smart_delay(...), so smart_delay(measurement.addvalue, time.time()) will first get the return value from time.time() and pass that forward to smart_delay.
You need to pass the time.time function itself, and call it inside of the smart_delay method, instead of passing its return value:
import time
class Measurement():
values = []
def add_value(self, value):
print "added value"
self.values.append(value)
def smart_delay(output_f, input_f):
start_time = time.time()
while 5 > (time.time() - start_time):
print "Calling function"
output_f(input_f())
time.sleep(1)
measurement = Measurement()
smart_delay(measurement.add_value, time.time)
Notice, that this is not the best way to do what you're doing, but it works.
Here's how I'd do it:
import time
# Why do you need a measurement class which only acts as a list anyways?
my_measurements = []
def repeat(duration, function, args=(), kwargs={}, interval=1):
"""Repeat a function call for the given duration."""
start_time = time.time()
while duration > time.time() - start_time:
function(*args, **kwargs)
time.sleep(interval)
def add_time_measurement(measurements):
measurements.append(time.time())
repeat(5, add_time_measurement, (my_measurements,))
And if you want some prints, you can just add them in the add_time_measurement function.

Transfer variable between Python module

For example, I have a file called "gui.py", which uses a module, which is called "pytime.py".
They are in the same directory.
The module (time.py) code has two functions: settime() and readtime()
gui.py code looks like:
import pytime
pytime.settime(16,40) #set hour to 16:40
Now, I want that the other function in the pytime module (readtime()) could access the hour.
I tried "global" but it didn't helped, and also googled a lot.
Thanks!
if you want shared state between the functions, the best way to do this would probably be a class:
# pytime.py
class PyTime(object):
def __init__(self, hour=0, minute=0):
self._hour = hour
self._minute = minute
def set_time(self, hour=None, minute=None):
if hour is not None:
self._hour = hour
if minute is not None:
self._minute = minute
def read_time(self):
return self._hour, self._minute
def __str__(self):
return "{0._hour:02d}:{0._minute:02d}".format(self)
#property
def hour(self):
return self._hour
#property
def minute(self):
return self._minute
In use:
>>> timer = PyTime()
>>> timer.set_time(16, 40)
>>> timer.read_time()
(16, 40)
>>> timer.hour
16
>>> str(timer)
'16.40'
>>> timer.set_time(minute=30)
>>> str(timer)
'16:30'
>>> timer.hour = 15
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
timer.hour = 15
AttributeError: can't set attribute
Note this last result - as I define a property getter for hour but no setter, hour is immutable (although a determined user can access _hour directly).
You could pass in the variable into the function as such:
pytime.py:
def settime(hour, minute):
return str(hour)+':'+str(minute)
def readtime(hour):
print 'This is the hour: {0}'.format(hour)
gui.py:
import pytime
hour = pytime.settime(16, 40)
pytime.readtime(hour)
This runs as:
bash-3.2$ python gui.py
This is the hour: 16:40
bash-3.2$

Categories

Resources