Reputation: 65
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!
Upvotes: 0
Views: 73
Reputation: 61305
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
Upvotes: 1
Reputation: 369
try this,
test = 0
class Testing:
def add_one(self):
global test
test += 1
print(test)
t = Testing()
t.add_one()
Upvotes: 1
Reputation: 13
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()
Upvotes: 1
Reputation: 2590
You are not calling the function add_one
test = 0
class Testing:
def add_one():
global test
test += 1
Testing.add_one()
print (test)
Upvotes: 1