Python类:在调用实例时更新实例的值

时间:2016-04-26 22:40:23

标签: python class datetime

我正在玩类,并且已经创建了一个时间部分的脚本。

import datetime


class Timer(object):

    def __init__(self, *args, **kwargs):
        self.StartTime = datetime.datetime.now()
        self.TimeElapsed = self.timedif(datetime.datetime.now(), self.StartTime)

    def hms_string(self, sec_elapsed):
        h = int(sec_elapsed / (60 * 60))
        m = int((sec_elapsed % (60 * 60)) / 60)
        s = sec_elapsed % 60
        return "{}:{:>02}:{:>05.2f}".format(h, m, s)

    def timedif(self, end_datetime, start_datetime):
        seconds_elapsed = (end_datetime - start_datetime).total_seconds()
        return self.hms_string(seconds_elapsed)

我希望它能够打印自StartTime实例化Timer.TimeElapsed以来经过的时间量。当然,它的作用是打印00:00:00

如何修改我的课程,以便在我致电Timer.TimeElapsed时,它会使用实际当前时间与StartTime进行比较而不是调用课程的时间?

3 个答案:

答案 0 :(得分:1)

您可以将TimeElapsed替换为@property

@property
def TimeElapsed(self):
    return self.timedif(datetime.datetime.now(), self.StartTime)

不要忘记从self.TimeElapsed方法中移除__init__

另请注意,根据pep8,变量和方法名称不应位于CamelCase中。您的新媒体资源名为time_elapsed

答案 1 :(得分:0)

你可以改用一种方法:

import datetime
import time

class Timer(object):
    def __init__(self, *args, **kwargs):
        self.StartTime = datetime.datetime.now()
        self.TimeElapsed = self.timedif(datetime.datetime.now(), self.StartTime)

    def hms_string(self, sec_elapsed):
        h = int(sec_elapsed / (60 * 60))
        m = int((sec_elapsed % (60 * 60)) / 60)
        s = sec_elapsed % 60
        return "{}:{:>02}:{:>05.2f}".format(h, m, s)

    def timedif(self, end_datetime, start_datetime):
        seconds_elapsed = (end_datetime - start_datetime).total_seconds()
        return self.hms_string(seconds_elapsed)

    def time_elapsed(self):
        return self.timedif(datetime.datetime.now(), self.StartTime)

t = Timer()
print "time elapsed from variable: {}".format(t.TimeElapsed)
time.sleep(1)
print "time elapsed from variable: {}".format(t.TimeElapsed)

t = Timer()
print "time elapsed from method: {}".format(t.time_elapsed())
time.sleep(1)
print "time elapsed from method: {}".format(t.time_elapsed())

输出:

time elapsed from variable: 0:00:00.00
time elapsed from variable: 0:00:00.00
time elapsed from method: 0:00:00.00
time elapsed from method: 0:00:01.00

答案 2 :(得分:-1)

当您引用Timer.TimeElapsed时,您正在引用在类实例化时创建的类属性。