0

I've seen questions asked on this before, but I'm not able to recreate the alteration of global variables within a class function:

test = 0
class Testing:
    def add_one():
        global test
        test += 1

when I type in

Testing.add_one
print (test)

It prints "0". How do I get the function in the class to add one to test?

Thank you!

1
  • that's what I am doing Commented Oct 11, 2018 at 5:29

4 Answers 4

1

You are not calling the function add_one

test = 0    
class Testing:
    def add_one():
        global test
        test += 1
Testing.add_one()
print (test)
Sign up to request clarification or add additional context in comments.

Comments

1

You didn't call the function. And if you did you will get a TypeError

It should be like this

test = 0
class Testing(object):
    @staticmethod
    def add_one():
        global test
        test += 1

Testing.add_one()

Comments

1

try this,

enter image description here

test = 0
class Testing:
    def add_one(self):
        global test
        test += 1
        print(test)

t = Testing()
t.add_one()

Comments

1

You should call the method. Then only it will increment the value of the variable test.

In [7]: test = 0
   ...: class Testing:
   ...:     def add_one():
   ...:         global test
   ...:         test += 1                                                                                                                                                                

# check value before calling the method `add_one`
In [8]: test
Out[8]: 0

# this does nothing
In [9]: Testing.add_one
Out[9]: <function __main__.Testing.add_one()>

# `test` still holds the value 0
In [10]: test
Out[10]: 0

# correct way to increment the value
In [11]: Testing.add_one()

# now, check the value
In [12]: test
Out[12]: 1

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.