秒表实现python

时间:2016-10-04 17:54:40

标签: python python-3.x

我为这个作业获得了这段代码:

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")

我必须创建一个生成秒表的类,这是我的代码:

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))

我收到此错误:

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'

我做错了什么?我发现了一个错误。

1 个答案:

答案 0 :(得分:5)

您不能将您的功能和属性命名为相同的内容。执行self.stop = time.time()后,您将覆盖函数stop

您需要更改内部字段的名称。

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:你永远不会在你的代码中调用start。