首页 > 解决方案 > 如何从自定义类返回值以供以后使用?

问题描述

我用 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,然后对列表或其他内容求和。

我怎样才能做到这一点?

标签: pythonclasstime

解决方案


首先,你的类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

推荐阅读