MH. Abdi
MH. Abdi

Reputation: 308

Python cannot read global variable in function even though I used global keyword

I want to access the variable number_of_messages in class A but I get "number_of_messages" is not defined error even though I used global keyword. Here is a code sample:

class A:
    number_of_messages=0;
    def inc(self):
        global number_of_messages
        number_of_messages+=1
    
print(A().inc())

Upvotes: 2

Views: 62

Answers (2)

Guinther Kovalski
Guinther Kovalski

Reputation: 1919

Use the class attribute instead:

class A:
    def ___init__(self):
        self.number_of_messages=0

    def inc(self):
        self.number_of_messages+=1
a = A()
print(a.inc())
print(a.number_of_messages)

but you can also:

number_of_messages = 0

class A():
    def inc(self):
        global number_of_messages
        number_of_messages+=1

a = A()
a.inc()
print(number_of_messages)

you just forgot to declare the variable in the global scope

Upvotes: 3

Tim Roberts
Tim Roberts

Reputation: 54708

That's not a global. That's a class attribute. Write

    def inc(self):
        A.number_of_messages += 1

You don't need the global statement.

Upvotes: 1

Related Questions