简体   繁体   中英

Python global variable within function within class

I have a pubnub callback class (callback), with a message handler function (message) inside it. The handler function is called by pubnub when it receives a message, and it should take a variable which is defined outside of the class (in another class and function) and modify it based on the message that it has received from pubnub. This updated variable should remain globally available. I've tried putting global keywords all over the place, but it hasn't helped:

class callback(SubscribeCallback):  # Listener for channel list

    def message(self, pubnub, message):
        new_var = set(var) - set(message)
        # do stuff with new_var
        var = new_var #Update global variable (it doesn't, but it should!)


class other(django admin command thing):
    def command(self):
        var = ['a', 'b'] #Initial definition - this function is only called once

Where does the global keyword need to go to make this work? I can access and pop from var2, but I can't both read and write var...

You need to declare the variable as global in each context where it's referenced

>>> class A:
...     def test(self, m):
...             global X
...             X = X + m
...
>>> class B:
...     def __init__(self):
...             global X
...             X = "Y"
...
>>> b = B()
>>> X
'Y'
>>> a = A()
>>> a.test("Z")
>>> X
'YZ'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM