简体   繁体   English

Python3-使用函数参数作为变量名

[英]Python3 - use function parameter as name of variable

I have a function that creates different forms of arrays and I don't know how to differentiate them. 我有一个函数可以创建不同形式的数组,但我不知道如何区分它们。 Is something similar to this possible? 有可能与此类似吗?

def array_creator(nameArray):
    nameArray = [0,1,2]

array_creator(a)
print(a)  # prints [0,1,2]

At the moment I always run the function and then assign manually variables to store the arrays. 目前,我总是运行该函数,然后手动分配变量以存储数组。 Thanks! 谢谢!

For your example to work you need to define your variable a before you use it. 为了使示例正常工作,您需要在使用变量之前定义变量a Eg a = [] . 例如a = [] However your example won't work the way you want to. 但是,您的示例无法按您想要的方式工作。 The reason for this is that you assign a new object ( [1, 2, 3] ) to your nameArray variable in line 2. This way you lose the reference to your object a . 这样做的原因是,您在第2行中为nameArray变量分配了一个新对象( [1, 2, 3] )。这样就丢失了对对象a的引用。 However it is possible to change your object a from inside the function. 但是,可以从函数内部更改对象a

def array_creator(nameArray):
    nameArray.extend([0,1,2])

a = []
array_creator(a)
print(a)  # prints [0,1,2]

This will work. 这将起作用。 Have a look at How to write functions with output parameters for further information. 看看如何使用输出参数编写函数以获取更多信息。

In Python you do this by returning a value from the function and binding this value to a local name, ie: 在Python中,您可以通过从函数返回一个值并将该值绑定到本地名称来完成此操作,即:

def array_creator():
    return [0, 1, 2]

a = array_creator()

Python does not have "output parameters", hence a plain assignment will only change the binding of the local variable, but will not modify any value, nor change bindings of variables outside the function. Python没有“输出参数”,因此简单分配只会更改局部变量的绑定 ,而不会修改任何值,也不会更改函数外部变量的绑定。

However list s are mutable, so if you want to modify the argument just do so: 但是list是可变的,因此,如果要修改参数,只需执行以下操作:

nameArray[:] = [0,1,2]

This will replace the contents of nameArray with 0,1,2 (works if nameArray is a list ). 这会将nameArray的内容替换为0,1,2 (如果nameArraylist则可以使用)。

An alternative is to have your function simply return the value you want to assign: 一种替代方法是让您的函数简单地返回要分配的值:

def array_creator():
    values = [0, 1, 2]
    return values

my_arr = array_creator()

Finally, if the function wants to modify a global / nonlocal variable you have to declare it as such: 最后,如果函数要修改global / nonlocal变量,则必须这样声明:

a = [1,2,3]

def array_creator():
    global a
    a = [0,1,2]

print(a)   # [1,2,3]
array_creator()
print(a)   # [0,1,2]

Or: 要么:

def wrapper():
    a = [1,2,3]
    def array_creator():
        nonlocal a
        a = [0,1,2]
    return a, array_creator

a, creator = wrapper()

print(a)   # [1,2,3]
creator()
print(a)   # [0,1,2]

Note however that it is generally bad practice to use global variables in this way, so try to avoid it. 但是请注意,以这种方式使用全局变量通常是不好的做法 ,因此请避免使用它。

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

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