[python][原创]python函数怎么对int或者bool进行引用传递

Posted FL1623863129

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[python][原创]python函数怎么对int或者bool进行引用传递相关的知识,希望对你有一定的参考价值。

先看下面代码:

import time
import threading


def func(a):
    index=1
    while a:
        print('loop' + str(index))
        index += 1
        time.sleep(1)

a = True
threading.Thread(target=func, args=(a,)).start()
time.sleep(3)
a = False

上面代码你会发现循环停止不下来, 因为a是值传递。
解决方法:

import time
import threading


def func(a):
    index = 1
    while a[0]:
        print('===' + str(id(a)))
        print('loop' + str(index))
        index += 1
        time.sleep(1)


a = [True]
print('before=' + str(id(a)))
threading.Thread(target=func, args=(a,)).start()
time.sleep(3)
a[0] = False
print('after=' + str(id(a)))

以上是关于[python][原创]python函数怎么对int或者bool进行引用传递的主要内容,如果未能解决你的问题,请参考以下文章

python中的for i in range怎么用

python是不是有绘制混淆矩阵的函数,怎么来实现

map函数的用法python需要引入啥库

python中的for i in range怎么用

Introduction of Generator in Python

python中的for i in range怎么用?