[英]Is there a way to define a variable that is a parameter inside a function in Python?
Is it possible to define a variable that is a parameter inside a function? 是否可以定义作为函数内部参数的变量? I've tried doing this: 我尝试这样做:
def myfunc(variable):
variable = 5
myfunc(x)
print(x)
I was expecting to see the number "5" printed on my screen, because I'm defining x (which is 5) and then printing it. 我期望在屏幕上看到数字“ 5”,因为我正在定义x(即5)然后进行打印。 But I get this NameError: 但是我得到这个NameError:
Traceback (most recent call last):
File "C:\Users\yoelc\PycharmProjects\Test\app.py", line 4, in <module>
myfunc(x)
NameError: name 'x' is not defined
I know it is possible to do this: 我知道可以这样做:
def myfunc():
return 5
x = myfunc()
print(x)
But that's not what I'm trying to do. 但这不是我要尝试的。 Is there a way to define this? 有没有办法定义这个?
Maybe not exactly what you want but pretty similar: 也许不完全是您想要的,但非常相似:
def myfunc(variable):
globals()[variable] = 5
myfunc('x')
print(x)
That being said this is a bad idea, unless you really need to use metaprogramming for some reason 话虽这么说,这是一个坏主意,除非您出于某种原因确实需要使用元编程
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.