python - 类实例的成员未更新
问题描述
我有一个带有成员变量的类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,尽管它每秒都在更新。
有人可以帮我吗?
解决方案
实际上,您并没有开始您的流程t1.start()
,而ThreadRunner
您正在使用的方法while True
将持续运行。
推荐阅读
- javascript - React 需要处理一些 if 条件
- apache-kafka - kafka 和 schema 注册表如何共享 KafkaProperties?(提供了“basic.auth.user.info”,但不是已知配置。)
- spring - @WebMvcTest vs @ContextConfiguration when testing WebSocket controllers
- apache - htaccess – FALSE If statement still runs
- json - How to write a sentence into JSON file in Qt not necessarily in JSON format?
- python - ModuleNotFoundError: No module named 'numpy.testing.nosetester' AND PermissionError: [WinError 5] Access is denied
- c - How to emit debug information using llvm ir in Clang?
- c# - Filling DataTable column by column C#
- json - Passing X-Authentication via CURL on command line
- python - What is the correct way to reproject a raster from a CRS to another using Python?