2

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())

2
  • 1
    It isn't defined. Why do you expect a global variable with that name to exist? Commented Dec 17, 2021 at 20:01
  • 1
    note: your inc method returns None, so I would never expect your print statement to shed light on what's happening with number_of_messages Commented Dec 17, 2021 at 20:07

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.