[英]changing a global variable within a class function in python
我之前已經看過有關此問題的問題,但無法在類函數中重新創建全局變量的更改:
test = 0
class Testing:
def add_one():
global test
test += 1
當我輸入
Testing.add_one
print (test)
打印“ 0”。 如何在類中獲取要添加的功能以進行測試?
謝謝!
您沒有在調用函數add_one
test = 0
class Testing:
def add_one():
global test
test += 1
Testing.add_one()
print (test)
您沒有調用該函數。 如果您這樣做了,則會收到TypeError
應該是這樣
test = 0
class Testing(object):
@staticmethod
def add_one():
global test
test += 1
Testing.add_one()
您應該調用該方法。 然后只有它會增加變量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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.