Python变量“重置" [英] Python Variable "resetting"

查看:32
本文介绍了Python变量“重置"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将一个字符串设置为函数中的某个内容,然后尝试将其打印到另一个函数中,以发现该字符串从未改变.我做错了什么吗?

I am setting a string to something in a function, then trying to print it in another to find that the string never changed. Am I doing something wrong?

在我的脚本顶部定义变量

Defining the variable at the top of my script

CHARNAME = "Unnamed"

函数设置变量

def setName(name):
        CHARNAME = name
        print CHARNAME

函数的使用

print CHARNAME
setName("1234")
print CHARNAME

输出

Unnamed
1234
Unnamed

推荐答案

当您在 setName 函数中执行 CHARNAME = name 时,您只是在定义它 用于该范围.即,它不能在函数之外访问.因此,global 变量 CHARNAME(值为 "Unnamed" 的那个)未受影响,您在调用后继续打印其内容功能

When you do CHARNAME = name in the setName function, you are defining it only for that scope. i.e, it can not be accessed outside of the function. Hence, the global vriable CHARNAME (the one with the value "Unnamed"), is untouched, and you proceed to print its contents after calling the function

您实际上并未覆盖全局变量CHARNAME.如果你愿意,你必须在定义它之前通过把 global CHARNAME 放在函数 setName 中来全球化变量 CHARNAME:

You aren't actually overwriting the global variable CHARNAME. If you want to, you must globalise the variable CHARNAME in the function setName by putting global CHARNAME before you define it:

def setName(name):
    global CHARNAME
    CHARNAME = name
    print CHARNAME

或者,您可以从函数中返回CHARNAME的值:

Alternatively, you can return the value of CHARNAME from the function:

def setName(name):
    return name

CHARNAME = setName('1234')

当然这是没用的,你也可以这样做 CHARNAME = '1234'

Of course this is rather useless and you might as well do CHARNAME = '1234'

这篇关于Python变量“重置"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆