在python中的类函数中更改全局变量

我之前看过有关此问题的问题,但我无法在类函数中重新创建全局变量的更改:


test = 0

class Testing:

    def add_one():

        global test

        test += 1

当我输入时


Testing.add_one

print (test)

它打印“0”。如何获取类中的函数以添加一个进行测试?


慕码人8056858
浏览 467回答 3
3回答

森林海

你没有调用函数。如果你这样做了,你会得到一个 TypeError应该是这样的test = 0class Testing(object):    @staticmethod    def add_one():        global test        test += 1Testing.add_one()

白衣染霜花

您应该调用该方法。那么只有它会增加变量的值test。In [7]: test = 0&nbsp; &nbsp;...: class Testing:&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp;def add_one():&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;global test&nbsp; &nbsp;...:&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;test += 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;&nbsp;# check value before calling the method `add_one`In [8]: testOut[8]: 0# this does nothingIn [9]: Testing.add_oneOut[9]: <function __main__.Testing.add_one()># `test` still holds the value 0In [10]: testOut[10]: 0# correct way to increment the valueIn [11]: Testing.add_one()# now, check the valueIn [12]: testOut[12]: 1

吃鸡游戏

试试这个,test = 0class Testing:&nbsp; &nbsp; def add_one(self):&nbsp; &nbsp; &nbsp; &nbsp; global test&nbsp; &nbsp; &nbsp; &nbsp; test += 1&nbsp; &nbsp; &nbsp; &nbsp; print(test)t = Testing()t.add_one()
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python