为什么这个classscope变量在递归函数中没有得到更新?

2024-09-30 00:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个LED控制器编写一个小类,它作为一个进程运行。这个想法是一些代码在i2c总线上不断运行以闪烁LED

我不熟悉Python的OOP,也不熟悉Python中的进程。我在python3.4中使用了多处理,但是新的print函数也应该在2.7x中运行

如果您运行代码,我会在blinkgroup列表中添加三个内容,在本地显示有效果,但是在ledbinkloop函数中从未检测到这一点,该函数会调用自身以使其保持运行

我怀疑我根本不理解Python中的某些东西

from multiprocessing import Process, Queue
import time

class LedController(Process):
    def __init__(self):     
        super(LedController, self).__init__()
        print("ledcontroller started: ",self.name)
        self.blinkgroup = [0x04,0x05]

    def run(self):
        self.ledblinkloop()

    def led_blink_on(self,led):
        if(led not in self.blinkgroup):
            print("LED not in blink group, adding. New blinkgroup length:",len(self.blinkgroup))
            self.blinkgroup.append(led)

    def ledblinkloop(self):
        print("Length of blinkgroup:",len(self.blinkgroup))
        time.sleep(1)
        self.ledblinkloop()

class myclass:
    def __init__(self):
        ledcontroller = LedController()
        ledcontroller.start()

        while(1):
            time.sleep(5)
            ledcontroller.led_blink_on(0x08)
            ledcontroller.led_blink_on(0x09)
            ledcontroller.led_blink_on(0x10)
            time.sleep(5)

if __name__ == "__main__":

代码应该按照python3的原样运行


Tags: 函数代码selfledtimeinitondef
1条回答
网友
1楼 · 发布于 2024-09-30 00:27:11

多处理库通过生成额外的Python进程来工作。他们不共享记忆

我看到您确实从多处理库导入了Queue,但没有继续使用它。Queue是在Process之间进行通信的两种方式之一,另一种是Pipe

可能值得在继续之前通读多处理库的documentation

相关问题 更多 >

    热门问题