【问题标题】:Change variable in function (Python 3.x)更改函数中的变量(Python 3.x)
【发布时间】:2023-04-03 18:06:01
【问题描述】:

如果你有这样的python代码:

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

my_func(thing)

print(thing)

那么变量 'thing' 将只返回 'string' 而不是新输入的内容。如何在不列出实际变量名的情况下更改它?

【问题讨论】:

  • 您应该从函数中返回一个值并将其分配给变量。 thing = my_func()
  • 你传值的参数,必须返回值再赋值给变量:thing = "string" def my_func(variable): variable = input("Type something.") return variable thing = my_func(thing) print(thing)

标签: python python-3.x function


【解决方案1】:

变量的范围有问题。

thing 作为函数内部的变量在这里没有任何用处,因为它不能通过调用任何函数来更改,除非您专门定义函数以仅更改thing 的值。

你可以用一种方式定义它:

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'

但上述方法只适用于thing 变量。而不是传递给它的任何其他变量,但像下面这样的函数将适用于所有内容。

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

【讨论】:

  • 不宜将函数名用作变量:input = input("Type something."))a 是什么?
  • @eyllanesc 抱歉,我更正了,您有什么改进建议吗?
  • 全局变量的使用会带来难以追踪的问题,所以我尽量避免使用,推荐使用,除非变量是唯一的,不推荐初学者使用,因为容易滥用. :D
猜你喜欢
  • 2017-01-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-14
  • 1970-01-01
  • 1970-01-01
  • 2015-12-15
相关资源
最近更新 更多