python - 如何从自定义类返回值以供以后使用?
问题描述
我用 Python 写了一个类:
class TimeError(Exception):
"""A custom exception used to report errors in use of Timer Class"""
class simulation_timer:
def __init__(self):
self._simulation_start_time = None
self._simulation_stop_time = None
def start(self):
"""start a new timer"""
if self._simulation_start_time is not None: # attribute
raise TimeError(f"Timer is running.\n Use .stop() to stop it")
self._simulation_start_time = time.perf_counter()
def stop(self):
"""stop the time and report the elsaped time"""
if self._simulation_start_time is None:
raise TimeError(f"Timer is not running.\n Use .start() to start it.")
self._simulation_stop_time = time.perf_counter()
elapsed_simulation_time = self._simulation_stop_time - self._simulation_start_time
self._simulation_start_time = None
print(f"Elapsed time: {elapsed_simulation_time:0.4f} seconds")
这让我可以测量我的代码某些部分的执行时间。该类仅打印时间值。我现在需要return
一个值,这样我就可以将脚本不同部分的测量执行时间加起来,方法是将它们写入 a 中list
,然后对列表或其他内容求和。
我怎样才能做到这一点?
解决方案
首先,你的类TimeError
有一个缩进错误,并且至少需要一个pass
语句。其次,按照惯例(PEP 8),你的类simulation_timer
最好命名为SimulationTimer
.
最简单的方法是包含一个附加属性accumulated_elpased_time
,初始化为0.0
。该stop
方法只是将当前的elapsed_simulation_time
. 实现了一种新方法get_accululated_time
来检索此属性值:
import time
class TimeError(Exception):
"""A custom exception used to report errors in use of Timer Class"""
pass
class SimulationTimer:
def __init__(self):
self._simulation_start_time = None
self._simulation_stop_time = None
self.accumulated_elpased_time = 0.0
def start(self):
"""start a new timer"""
if self._simulation_start_time is not None: # attribute
raise TimeError(f"Timer is running.\n Use .stop() to stop it")
self._simulation_start_time = time.perf_counter()
def stop(self):
"""stop the time and report the elsaped time"""
if self._simulation_start_time is None:
raise TimeError(f"Timer is not running.\n Use .start() to start it.")
self._simulation_stop_time = time.perf_counter()
elapsed_simulation_time = self._simulation_stop_time - self._simulation_start_time
self.accumulated_elpased_time += elapsed_simulation_time
self._simulation_start_time = None
print(f"Elapsed time: {elapsed_simulation_time:0.4f} seconds")
def get_accumulated_time(self):
"""get accumulated elsaped time"""
return self.accumulated_elpased_time
simulation_timer = SimulationTimer()
simulation_timer.start()
time.sleep(3)
simulation_timer.stop()
simulation_timer.start()
time.sleep(2)
simulation_timer.stop()
print(f"Accumulated time: {simulation_timer.get_accumulated_time():0.4f} seconds")
印刷:
Elapsed time: 2.9992 seconds
Elapsed time: 1.9997 seconds
Accumulated time: 4.9989 seconds
推荐阅读
- google-app-engine - App Engine - 是否必须使用预热请求才能使用 min_instances?
- xml - 为密钥设置 xsd 并验证 xml
- node.js - 同步/异步功能和冻结的后台循环
- elasticsearch - Elastic Search - Count api 显示不正确的索引文档总数
- javascript - 从捆绑在一起的 JS 模块中指向公共依赖项的最佳方法是什么?
- leaflet - 在传单中放大和显示/隐藏标签
- vba - 如果没有回复,如何发送后续电子邮件?
- java - Hibernate JPA 映射相同类型的多个实体
- ruby - bsearch_index 的奇怪行为
- java - 放心尝试发布多种文件格式但收到 415 响应代码