您好,感謝您的幫助:)
題
我的問題是,為什么task.print_times()正確列印經過的時間......
2022-02-24 21:35:23
2022-02-24 21:35:26
0:00:03
但是task.dict_times()列印這個...
{
'time_start': '2022-02-24 21:35:23',
'time_end': '2022-02-24 21:35:26',
'time_elapsed': datetime.timedelta(seconds=3)
}
代碼
from datetime import timedelta
from timeit import default_timer as timer
from time import strftime, localtime, sleep
class Timer:
'''A utility class for capturing a task's processing time.
'''
def __init__(self):
self.start_timer = None
self.time_start = None
self.stop_timer = None
self.time_stop = None
self.time_elapsed = None
def start(self):
'''Start the timer and capture the start time.
'''
self.start_timer = timer()
self.time_start = strftime("%Y-%m-%d %H:%M:%S", localtime())
def stop(self):
'''Stop the timer and capture the stop time.
'''
self.stop_timer = timer()
self.time_stop = strftime("%Y-%m-%d %H:%M:%S", localtime())
def elapsed(self):
'''Calculates the elapsed time.
'''
elapsed = timedelta(seconds=self.stop_timer-self.start_timer)
self.time_elapsed = elapsed - timedelta(microseconds=elapsed.microseconds)
# --------------------------
# Example usage
# --------------------------
class Task:
def __init__(self):
self.task_timer = Timer()
self.time_summary = {}
def do(self):
self.task_timer.start()
sleep(3)
self.task_timer.stop()
self.task_timer.elapsed()
def print_times(self):
print(self.task_timer.time_start)
print(self.task_timer.time_stop)
print(self.task_timer.time_elapsed)
def dict_times(self):
self.time_summary['time_start'] = self.task_timer.time_start
self.time_summary['time_end'] = self.task_timer.time_stop
self.time_summary['time_elapsed'] = self.task_timer.time_elapsed
print(self.time_summary)
task = Task()
task.do()
task.print_times()
task.dict_times()
uj5u.com熱心網友回復:
__repr__列印字典時,會根據其方法回傳的值列印其中的各個鍵/元素。當您直接列印物件時,將__str__呼叫該方法。
考慮這個簡單的例子:
class Foo:
def __str__(self):
return 'foo'
def __repr__(self):
return 'bar'
x = Foo()
d = {'a': x}
print(x) # -> foo
print(d) # -> {'a': bar}
這個問題很好地解釋了str/__str__和repr/之間的區別__repr__。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/432391.html
