简体   繁体   English

更改函数中的变量(Python 3.x)

[英]Change variable in function (Python 3.x)

If you have python code like this: 如果您有这样的python代码:

thing = "string"
def my_func(variable):
    variable = input("Type something.")

my_func(thing)

print(thing)

Then the variable 'thing' will just return 'string' and not what the new input is. 然后,变量“ thing”将仅返回“ string”,而不是新输入的内容。 How can I change it without listing the actual variable name? 如何在不列出实际变量名的情况下进行更改?

You have problems with scopes of variables. 您在变量范围方面遇到问题。

Taking in the thing as a variable inside your function isn't any useful here as it can't be changed just by calling any function until you specifically define the function to change only the value of thing . thing中将thing作为变量包含在这里没有任何用处,因为不能仅仅通过调用任何函数来更改它,除非您专门定义该函数以仅改变thing的值。

You can define it in one way as: 您可以通过以下方式之一对其进行定义:

thing = "string"
def my_func():
    global thing #As thing has a global scope you have to tell python to modify it globally
    thing = input("Type something:")
>>>my_func()
>>>Type something: hello world
>>>print(thing)
>>>'Hello world'

But the above method will only work for the thing variable. 但是上述方法仅适用于thing变量。 And not on any other variables passed to it, but a function like below will work on everything. 而不是传递给它的任何其他变量,但是下面的函数将对任何东西都起作用。

thing = "string"
def my_func():
    a = input("Type something."))
    return a
>>>thing = my_func()
>>>Type something: Hello world
>>>print(thing)
>>>'Hello world'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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