[英]Python global variables : too global for me
Below, I would like the s
var be global to the f
function, but local to the principal
function.下面,我希望
s
var 对于f
function 是全局的,但对于principal
function 是本地的。
It seems global
means "The Most Global in the Module".似乎
global
意味着“模块中最全球化”。 How can I make one less global scope?我怎样才能少一个全局 scope?
s="what the hell"
print(s)
def principal():
s ="hey"
def f():
global s
if len(s) < 8:
s += " !"
f()
f()
return s
print(principal())
what the hell
hey
I'm not sure if this is what you are going for, since global
has an unambiguous meaning in Python. If you want to modify the variable s
as defined in principal()
within f()
you can use nonlocal
:我不确定这是否是您想要的,因为
global
在 Python 中具有明确的含义。如果您想修改f()
principal()
中定义的变量s
,您可以使用nonlocal
:
s="what the hell"
print(s)
def principal():
s = "hey"
def f():
nonlocal s
if len(s) < 8:
s += " !"
f()
f()
return s
print(principal())
But the real goal here would probably be, to avoid constructs like that altogether and pass the respective variables as arguments and return the modified values from (pure) functions.但这里的真正目标可能是,完全避免这样的构造,并将相应的变量作为 arguments 传递,并从(纯)函数返回修改后的值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.