如何在python中的局部变量中存储全局变量名?

时间:2017-01-29 20:01:23

标签: python python-2.7 global

所以我试图创建一个让我简单地调用函数的函数,并给它10个值和一个变量,它会将该变量随机变为其中一个值。

import random

place = "NA"

def randomize (value1, value2, value3, value4, value5, value6, value7, value8, value9, value10, variable):
global variable
variable  = random.choice([value1, value2, value3, value4, value5, value6, value7, value8, value9, value10])

randomize ("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom", place)

print place

然而,这告诉我以下内容:

SyntaxError: name 'variable' is local and global

3 个答案:

答案 0 :(得分:0)

实现目标的一种方法是不将全局变量place作为函数中的参数传递

import random

place = "NA"

def randomize (value1, value2, value3, value4, value5, value6, value7, value8, value9, value10):      
   global place       
   place  = random.choice([value1, value2, value3, value4, value5, value6, value7, value8, value9, value10])

randomize ("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom")

print place

修改

正如您已指出要将此函数用于其他变量一样,为此,您只需返回random.choice....并调用randomize函数即可更改任意数量的值你想要的变量。

以下代码段用于更改两个变量的值,一个是全局变量place,另一个是myVar

import random

place = "NA"

def randomize (value1, value2, value3, value4, value5, value6, value7, value8, value9, value10):
    return random.choice([value1, value2, value3, value4, value5, value6, value7, value8, value9, value10])

place = randomize ("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom")

myVar = randomize ("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom")

print place   
print myVar

答案 1 :(得分:0)

在Python中,通常不会修改输入参数。我知道这是C中的标准,但是更容易返回值并将变量赋值给函数的输出:

import random

def randomize(*values):
    return random.choice(values)

place = "NA"
print place

place = randomize("Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks", "Warehouse", "ThroneRoom", "Bedroom")
print place

答案 2 :(得分:0)

对于1, 2, 3, ... n值,您应该使用list。您还需要编写更少的代码,因此它可以更好地扩展。你应该尽量避免global variables ......你可以找到in the global internet的原因。对于此示例,您甚至可以保存方法定义。

import random
places = ["Dungeon", "Plains", "Castle", "Prison", "Tavern", "Armory", "Docks",
          "Warehouse", "ThroneRoom", "Bedroom"]  # list with n elements...
place = random.choice(places)
print place