Using variables in signal handler - require global?

后端 未结 5 1759
不思量自难忘°
不思量自难忘° 2021-01-01 10:10

I have a signal handler to handle ctrl-c interrupt. If in the signal handler I want to read a variable set in my main script, is there an alternative to using a \"global\" s

5条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-01 10:58

    If you're just reading the variable, there should be no need to make the variable "global"

    def foo():
        print a
    a = 3
    foo()  #3
    

    global is necessary to allow you to change the variable and have that change propagate into the module namespace.

    If you want to pass some state to your callback without using global, the typical way to do this us to use an instance method as the callback:

    class foo(object):
         def __init__(self,arg):
             self.arg = arg
         def callback_print_arg(self):
             print self.arg
    
    def call_callback(callback):
        callback()
    
    a = foo(42)
    call_callback(a.callback_print_arg) #42
    

提交回复
热议问题