简体   繁体   English

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

[英]changing a global variable within a class function in python

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". 打印“ 0”。 How do I get the function in the class to add one to test? 如何在类中获取要添加的功能以进行测试?

Thank you! 谢谢!

You are not calling the function add_one 您没有在调用函数add_one

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

You didn't call the function. 您没有调用该函数。 And if you did you will get a TypeError 如果您这样做了,则会收到TypeError

It should be like this 应该是这样

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

Testing.add_one()

try this, 尝试这个,

在此处输入图片说明

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

t = Testing()
t.add_one()

You should call the method. 您应该调用该方法。 Then only it will increment the value of the variable test . 然后只有它会增加变量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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM