首页 > 解决方案 > 类实例的成员未更新

问题描述

我有一个带有成员变量的类self._duration,我通过在进程中调用它的一个方法来定期更新它。类定义如下:


class Tracker :

    def __init__(self):
        self._duration = 0
        
    
    def UpdateDuration(self):
        self._duration += 1
        print ("updated the duration to : {0}".format(self._duration))
    
    def GetDuration(self):
        return self._duration 
  
    def ThreadRunner(self) :
        while True :
            self.UpdateDuration()
            time.sleep(1)

我在另一个文件中创建了一个类的实例并开始如下过程

trip = False 
end = False

while not trip :
    start = input("do you want to start the trip? : ")
    if start.lower() == "start" :
        trip = True


if trip :
    vt = Tracker()
    t1 = multiprocessing.Process(target = vt.ThreadRunner, args=())
    t1.start()


    inp = input("Enter any char if you want to end the trip : ")

    t1.terminate()
    
    print ("Trip duration : {0}".format(vt.GetDuration()))

我的问题是,每次UpdateDuration调用该方法时,我都会收到一条声明,说明持续时间已更新为预期值。但是当旅程最终结束时,该GetDuration方法返回 0,尽管它每秒都在更新。

有人可以帮我吗?

标签: pythonpython-3.x

解决方案


实际上,您并没有开始您的流程t1.start(),而ThreadRunner您正在使用的方法while True将持续运行。


推荐阅读