Python线程和传递引用

时间:2018-07-06 18:19:50

标签: python multithreading

如何传递对类的实例化(自身)的引用。我仍在学习Python,还没有弄清楚。

我有两个警报,并且希望使其自动运行,并在后台连续运行。如果我可以打电话给他们以执行某些操作,那将是很好的。

基本上,这为什么不起作用?

from time import sleep
import threading

class alarm:

    def __init__(self, interval):
        self.activated = False
        self.sound = "Beeeep"
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):
        # this runs forever
        while True:
            if self.activated:
                print(self.sound)
            else:
                print("(quiet)")
            sleep(self.interval)

    def on(self):
        self.activated = True

    def off(self):
        self.activated = False

    def set_beep(self, sound):
        self.sound = sound


def main():

    a1 = alarm(.5)
    a2 = alarm(.5)

    print("Waiting 3 secs")
    sleep(3)
    print("Turning on alarm1")
    a1.on

    sleep(2)
    print("Turning on alarm2")
    a2.on

    sleep(2)
    print("Turning off alarms")
    a1.off
    a2.off

    print("Waiting 10 seconds")
    sleep(10)


if __name__ == '__main__':
    main()

输出为:

(安静) (安静) 等待3秒 (安静) (安静) (安静) (安静) (安静) (安静) (安静) (安静) (安静) (安静) 打开警报1 (安静) (安静) (安静)

它不会打开任何一个警报。

2 个答案:

答案 0 :(得分:2)

之所以发生这种情况,是因为您没有将方法调用为“ on”和“ off”,要调用一个方法,您必须在其后插入一对括号,并在其中插入任何参数。

def main():

a1 = alarm(.5)
a2 = alarm(.5)

print("Waiting 3 secs")
sleep(3)
print("Turning on alarm1")
a1.on()

sleep(2)
print("Turning on alarm2")
a2.on()

sleep(2)
print("Turning off alarms")
a1.off()
a2.off()

print("Waiting 10 seconds")
sleep(10)

答案 1 :(得分:0)

您不会使用a1.on和a1.off调用函数,而只是将它们分配为空。 为了进一步说明,

a1.on is basically "" = a1.on

如果要输入例如:

a = a1.on

然后将功能a1.on分配给a,因此:

a()

然后将执行与

相同的功能
a1.on()

所以:

from time import sleep
import threading

class alarm:
    def __init__(self, interval):
        self.activated = False
        self.sound = "Beeeep"
        self.interval = interval

        thread = threading.Thread(target=self.run, args=())
        thread.daemon = True
        thread.start()

    def run(self):
        # this runs forever
        while True:
            if self.activated:
                print(self.sound)
            else:
                print("(quiet)")
            sleep(self.interval)

    def on(self):
        self.activated = True

    def off(self):
        self.activated = False

    def set_beep(self, sound):
        self.sound = sound

def main():

    a1 = alarm(.5)
    a2 = alarm(.5)

    print("Waiting 3 secs")
    sleep(3)
    print("Turning on alarm1")
    a1.on()

    sleep(2)
    print("Turning on alarm2")
    a2.on()

    sleep(2)
    print("Turning off alarms")
    a1.off()
    a2.off()

    print("Waiting 10 seconds")
    sleep(10)

if __name__ == '__main__':
    main()